1. 首页
  2. 技术文章

28、Python字典

在本教程中,您将学习有关Python字典的所有知识;如何创建,访问,添加,删除元素以及各种内置方法。

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'])

输出

Jack
26
None
Traceback (most recent call last):
  File "<string>", line 15, in <module>
    print(my_dict['address'])
KeyError: 'address'

更改和添加字典元素

字典是可变的。我们可以使用赋值运算符添加新项或更改现有项的值。

如果密钥已经存在,那么现有值将被更新。如果键不存在,则将新的(key:value)对添加到字典中。

# 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

Python字典方法

下表列出了词典可用的方法。在上面的示例中已经使用了其中一些。

方法 描述
清除() 从字典中删除所有项目。
复制() 返回字典的浅表副本。
fromkeys(seq [,v]) 返回一个新字典,其中的键来自 序列 且值等于 v(默认为None)。
get(key [,d]) 返回的值 钥匙。如果钥匙 不存在,返回 d(默认为None)。
项目() 以(键,值)格式返回字典项的新对象。
keys() 返回字典键的新对象。
弹出(键[,d]) 钥匙 并返回其值或 d 如果 钥匙找不到。如果d 没有提供,并且 钥匙找不到,它引发KeyError
popitem() 删除并返回一个任意项(key,value)。KeyError如果字典为空则引发。
setdefault(key [,d]) 如果 钥匙在字典中。如果不是,则插入钥匙 的值为 d 并返回 d(默认为None)。
更新([其他]) 使用以下项中的键/值对更新字典 其他,覆盖现有密钥。
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字典理解

字典理解是从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}

词典理解可以选择包含更多forif语句。

可选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字典理解


其他字典操作

字典成员资格测试

我们可以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)

输出

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(),等。通常使用词典用于执行不同的任务。

功能 描述
全部() 返回True如果字典的所有键都是真(或如果字典是空的)。
任何() True如果字典的任何键为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]
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站不拥有所有权,不承担相关法律责任。如发现有侵权/违规的内容, 联系QQ1841324605,本站将立刻清除。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

联系我们

服务热线:130-0886-1890

QR code