search
HomeBackend DevelopmentPython Tutorial整理Python最基本的操作字典的方法

Python 中的字典是Python中一个键值映射的数据结构,下面介绍一下如何优雅的操作字典.
1.1 创建字典

Python有两种方法可以创建字典,第一种是使用花括号,另一种是使用内建 函数dict

>>> info = {}
>>> info = dict()

1.2 初始化字典

Python可以在创建字典的时候初始化字典

>>> info = {"name" : 'cold'}
>>> info = dict(name = 'cold')    # 更优雅

很明显第二种方法更加的优雅和减少一些特殊字符的输入,但是有种情况第二种不能胜任

>>> key = 'name'
>>> info = { key :'cold'} # {'name':'cold'}
>>> info = dict(key = 'cold') # {'key': 'cold'}

明显第二种方法就会引发一个不容易找到的bug

Python字典还有一种初始化方式,就是使用字典的fromkeys方法可以从列表中获取元素作为键并用None或fromkeys方法的第二个参数初始化

>>> info = {}.fromkeys(['name', 'blog'])
>>> info
{'blog': None, 'name': None}
>>> info = dict().fromkeys(['name', 'blog'])
>>> info
{'blog': None, 'name': None}
>>> info = dict().fromkeys(['name', 'blog'], 'linuxzen.com')
>>> info
{'blog': 'linuxzen.com', 'name': 'linuxzen.com'}

1.3 优雅的获取键值

字典可以这样获取到键的值

>>> info = {'name':'cold', 'blog':'linuxzen.com'}
>>> info['name']
'cold'

但是如果获取不存在的键的值就会触发的一个KeyError异常,字典有一个get方法,可以使用字典get方法更加优雅的获取字典

>>> info = dict(name= 'cold', blog='www.linuxzen.com')
>>> info.get('name')
'cold'
>>> info.get('blogname')
None
>>> info.get('blogname', 'linuxzen')
'linuxzen'

我们看到使用get方法获取不存在的键值的时候不会触发异常,同时get方法接收两个参数,当不存在该键的时候就会返回第二个参数的值 我们可以看到使用get更加的优雅
1.4 更新/添加

Python 字典可以使用键作为索引来访问/更新/添加值

>>> info = dict()
>>> info['name'] = 'cold'
>>> info['blog'] = 'linuxzen.com'
>>> info
{'blog': 'linuxzen.com', 'name': 'cold'}
>>> info
{'blog': 'linuxzen.com', 'name': 'cold night'}

同时Python字典的update方法也可以更新和添加字典

>>> info = dict(name='cold', blog='linuxzen.com')
>>> info.update({'name':'cold night', 'blogname':'linuxzen'})
>>> info
{'blog': 'linuxzen.com', 'name': 'cold night', 'blogname': 'linuxzen'}
>>> info.update(name='cold', blog='www.linuxzen.com') # 更优雅
>>> info
{'blog': 'www.linuxzen.com', 'name': 'cold', 'blogname': 'linuxzen'}

Python字典的update方法可以使用一个字典来更新字典,也可以使用参数传递类似dict函数一样的方式更新一个字典,上面代码中哦功能的第二个更加优雅,但是同样和dict函数类似,键是变量时也只取字面值
1.5 字典删除

可以调用Python内置关键字del来删除一个键值

>>> info = dict(name='cold', blog='linuxzen.com')
>>> info
{'blog': 'linuxzen.com', 'name': 'cold'}
>>> del info['name']
>>> info
{'blog': 'linuxzen.com'}

同时也可以使用字典的pop方法来取出一个键值,并删除

>>> info = dict(name='cold', blog='linuxzen.com')
>>> info.pop('name')
'cold'
>>> info
{'blog': 'linuxzen.com'}

1.6 其他操作

获取所有key

>>> info = dict(name='cold', blog='linuxzen.com')
>>> info.keys()
['blog', 'name']

获取key,value并循环

>>> info = dict(name='cold', blog='linuxzen.com')
>>> for key, value in info.items():
...   print key, ':', value
... 
blog : linuxzen.com
name : cold

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),