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'])输出
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'字典是可变的。 我们可以使用赋值运算符添加新项或更改现有项的值。
如果键已经存在,那么现有值将被更新。 如果键不存在,则将新的键值对添加到字典中。
# 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)输出:
{'name': 'Jack', 'age': 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}
{}
Traceback (most recent call last):
File "<string>", line 30, in <module>
print(squares)
NameError: name 'squares' is not defined下表列出了字典可用的方法。 在上面的示例中已经使用了其中一些。
| 方法 | 描述 |
|---|---|
clear() |
从字典中删除所有项目。 |
copy() |
返回字典的浅表副本。 |
fromkeys(seq[, v]) |
返回一个新字典,其中的键从seq开始,其值等于v(默认为None)。 |
get(key [, d]) |
返回key的值。 如果key不存在,则返回d(默认为None)。 |
items() |
以(键,值)格式返回字典项的新对象。 |
keys() |
返回字典键的新对象。 |
pop(key [, d]) |
如果没有找到key,则用key删除该项目并返回其值或d。 如果未提供d,但未找到key,则它将弹出KeyError。 |
popitem() |
删除并返回任意项(键值)。 如果字典为空,则抛出KeyError。 |
setdefault(key [, d]) |
如果key在字典中,则返回相应的值。 如果不是,则插入key,其值为d,然后返回d(默认为None)。 |
update([other]) |
使用other中的键/值对更新字典,覆盖现有键。 |
values() |
返回字典值的新对象 |
以下是这些方法的一些示例用例。
# 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())))输出:
{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']字典推导式是一种用 Python 中的可迭代对象创建新字典的简洁明了方法。
字典推导式由一个表达式对(键值)和大括号{}中的for语句组成。
这是制作字典的示例,其中每个项目都是一对数字及其平方。
# Dictionary Comprehension
squares = {x: x*x 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] = x*x
print(squares)输出:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}可选的if语句可以过滤出项以形成新字典。
以下是一些仅包含奇数项的字典的示例。
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)输出:
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}要了解更多字典推导式,请访问 Python 字典推导式。
我们可以使用关键字in来测试key是否在字典中。 请注意,成员资格测试仅适用于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)输出:
True
True
False我们可以使用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()等内置函数通常与字典一起使用以执行不同的任务。
| 函数 | 描述 |
|---|---|
all() |
如果字典的所有键均为True(或者字典为空),则返回True。 |
any() |
如果字典的任何键为真,则返回True。 如果字典为空,则返回False。 |
len() |
返回字典中的长度(项目数)。 |
cmp() |
比较两个字典的项目。 (在 Python 3 中不可用) |
sorted() |
返回字典中新排序的键列表。 |
以下是一些使用内置函数来处理字典的示例。
# 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))输出:
False
True
6
[0, 1, 3, 5, 7, 9]