Python 字典是一个无序的项目集合。字典的每一项都有一key/value对。
字典经过优化,可以在键已知时检索值。


创建 Python 字典

创建字典就像将项目放在{}用逗号分隔的花括号内一样简单。
一个项目有一个key和一个对应value的表示为一对(键:值)。
虽然值可以是任何数据类型并且可以重复,但键必须是不可变类型(字符串数字或具有不可变元素的元组)并且必须是唯一的。
# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: ‘apple’, 2: ‘ball’} # dictionary with mixed keys my_dict = {‘name’: ‘John’, 1: [2, 4, 3]} # using dict() my_dict = dict({1:’apple’, 2:’ball’}) # from sequence having each item as a pair my_dict = dict([(1,’apple’), (2,’ball’)])
从上面可以看出,我们还可以使用内置dict()函数创建字典。


从字典访问元素

虽然索引与其他数据类型一起使用来访问值,但字典使用keys. 键可以在方括号内使用,也可以[]与get()方法一起使用。
如果我们使用方括号[],KeyError则在字典中找不到键的情况下引发。另一方面,如果未找到密钥,则该get()方法返回None。

get vs [] for retrieving elements my_dict = {‘name’: ‘Jack’, ‘age’: 26} # Output: Jack print(my_dict[‘name’]) # Output: 26 print(my_dict.get(‘age’)) # Trying to access keys which doesn’t exist throws error # Output None print(my_dict.get(‘address’)) # KeyError print(my_dict[‘address’])
输出
杰克 26 没有任何 回溯(最近一次调用最后一次): 文件“”,第 15 行,在 中 打印(my_dict[‘地址’]) 密钥错误:’地址’


更改和添加字典元素

字典是可变的。我们可以使用赋值运算符添加新项目或更改现有项目的值。
如果键已经存在,则现有值会被更新。如果键不存在,一个新的(键:值)对被添加到字典中。

Changing and adding Dictionary Elements my_dict = {‘name’: ‘Jack’, ‘age’: 26} # update value my_dict[‘age’] = 27 #Output: {‘age’: 27, ‘name’: ‘Jack’} print(my_dict) # add item my_dict[‘address’] = ‘Downtown’ # Output: {‘address’: ‘Downtown’, ‘age’: 27, ‘name’: ‘Jack’} print(my_dict)
输出
{‘姓名’:’杰克’,’年龄’:27} {‘name’: ‘Jack’, ‘age’: 27, ‘address’: ‘Downtown’}


从字典中删除元素

我们可以使用pop()方法删除字典中的特定项目。此方法删除具有提供的项目key并返回value。
该popitem()方法可用于(key, value)从字典中删除和返回任意项目对。使用该clear()方法可以一次删除所有项目。
我们还可以使用del关键字来删除单个项目或整个字典本身。

Removing elements from a dictionary # create a dictionary squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove a particular item, returns its value # Output: 16 print(squares.pop(4)) # Output: {1: 1, 2: 4, 3: 9, 5: 25} print(squares) # remove an arbitrary item, return (key,value) # Output: (5, 25) print(squares.popitem()) # Output: {1: 1, 2: 4, 3: 9} print(squares) # remove all items squares.clear() # Output: {} print(squares) # delete the dictionary itself del squares # Throws Error print(squares)

输出
16 {1: 1, 2: 4, 3: 9, 5: 25} (5, 25) {1: 1, 2: 4, 3: 9} {} 回溯(最近一次调用最后一次): 文件“”,第 30 行,在 中 打印(正方形) NameError: 名称 ‘squares’ 未定义


Python 字典方法

下面列出了可用于字典的方法。其中一些已经在上面的例子中使用过。

方法 描述
清除() 从字典中删除所有项目。
复制() 返回字典的浅拷贝。
fromkeys(seq[, v]) 返回一个带有键的新字典来自 序列 和值等于 v(默认为None)。
得到(键[,d]) 返回值 钥匙. 如果钥匙 不存在,返回 d(默认为None)。
项目() 以(键,值)格式返回字典项的新对象。
键() 返回字典键的新对象。
弹出(键[,d]) 删除带有 钥匙 并返回其值或 d 如果 钥匙没有找到。如果d 不提供,并且 钥匙未找到,它引发KeyError.
弹出项() 删除并返回任意项(key, value)。KeyError如果字典为空则引发。
setdefault(key[,d]) 返回相应的值,如果 钥匙在字典里。如果不是,则插入钥匙 价值为 d 并返回 d(默认为None)。
更新([其他]) 使用来自的键/值对更新字典 其他,覆盖现有密钥。
值() 返回字典值的新对象

以下是这些方法的一些示例用例。

Dictionary Methods marks = {}.fromkeys([‘Math’, ‘English’, ‘Science’], 0) # Output: {‘English’: 0, ‘Math’: 0, ‘Science’: 0} print(marks) for item in marks.items(): print(item) # Output: [‘English’, ‘Math’, ‘Science’] print(list(sorted(marks.keys())))
输出
{‘数学’:0,’英语’:0,’科学’:0} (‘数学’, 0) (‘英语’, 0) (‘科学’, 0) [‘英语’、’数学’、’科学’]


Python字典理解

字典理解是一种优雅而简洁的方式,可以从 Python 中的可迭代对象创建新字典。
字典推导由一个表达式对(键:值)和for花括号内的语句组成{}。
这是一个示例,用于制作一个字典,其中每个项目都是一对数字及其平方。

Dictionary Comprehension squares = {x: xx for x in range(6)} print(squares)
*输出

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
这段代码相当于

squares = {} for x in range(6): squares[x] = xx print(squares)
*输出

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
字典理解可以选择包含更多的forif语句。
可选if语句可以过滤出项目以形成新字典。
这里有一些例子来制作只有奇数项的字典。

Dictionary Comprehension with if conditional odd_squares = {x: xx for x in range(11) if x % 2 == 1} print(odd_squares)
*输出

{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
要了解更多词典理解,请访问Python 词典理解


其他字典操作

字典成员测试

我们可以key使用关键字来测试 a是否在字典中in。请注意,成员资格测试仅适用于keys而不适用于values。

Membership Test for Dictionary Keys squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: True print(1 in squares) # Output: True print(2 not in squares) # membership tests for key only not value # Output: False print(49 in squares)
输出
真的 真的 错误的

遍历字典

我们可以使用循环遍历字典中的每个键for。

Iterating through a Dictionary squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} for i in squares: print(squares[i])
输出
1 9 25 49 81


字典内置函数

内置函数喜欢all(),any(),len(),cmp(),sorted(),等。通常使用词典用于执行不同的任务。

功能 描述
全部() 返回True如果字典的所有键都是真(或如果字典是空的)。
任何() True如果字典的任何键为真,则返回。如果字典为空,则返回False。
长度() 返回字典中的长度(项目数)。
cmp() 比较两个字典的项目。(在 Python 3 中不可用)
排序() 返回字典中键的新排序列表。

下面是一些使用内置函数处理字典的示例。

Dictionary Built-in Functions squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: False print(all(squares)) # Output: True print(any(squares)) # Output: 6 print(len(squares)) # Output: [0, 1, 3, 5, 7, 9] print(sorted(squares))
输出
错误的 真的 6 [0, 1, 3, 5, 7, 9]