亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python字典

Python 字典

在本教程中,您将了解有关 Python 字典的所有内容;它们是如何创建、访问、添加、从中删除元素以及各种内置方法的。

视频:存储键/值对的 Python 字典

Python 字典是项目的无序集合。字典的每一项都有一个 key/value 对。

字典经过优化,可以在知道键时检索值。


创建 Python 字典

创建字典就像将项目放在花括号中一样简单 {} 用逗号分隔。

一个项目有一个 key 和相应的 value 表示为一对 (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 不存在,一个新的 (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 字典方法

字典可用的方法如下表所示。其中一些已经在上面的例子中使用过。

方法 说明
clear() 从字典中删除所有项目。
复制() 返回字典的浅拷贝。
fromkeys(seq[, v]) 返回一个带有 seq 键的新字典 和值等于 v (默认为 None )。
get(key[,d]) 返回 key 的值 .如果 key 不存在,返回 d (默认为 None )。
items() 以(键,值)格式返回字典项的新对象。
keys() 返回字典键的新对象。
pop(key[,d]) 使用 key 删除项目 并返回其值或 d 如果 没有找到。如果 d 未提供且 key 未找到,它引发 KeyError .
popitem() 删除并返回任意项(key, value )。引发 KeyError 如果字典为空。
setdefault(key[,d]) 如果key返回对应的值 在字典里。如果没有,插入 key 值为 d 并返回 d (默认为 None )。
更新([其他]) 使用 other 中的键/值对更新字典 , 覆盖现有的键。
值() 返回字典值的新对象

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

# 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 中的可迭代对象创建新字典。

字典理解由一个表达式对 (key:value ) 后跟 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}

字典推导式可以选择性地包含更多的 for 或 if 语句。

可选的 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 是否在字典中使用关键字 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() 等通常与字典一起使用以执行不同的任务。

函数 说明
all() 返回 True 如果字典的所有键都是 True(或者如果字典为空)。
any() 返回True 如果字典的任何键为真。如果字典为空,则返回 False .
len() 返回字典中的长度(项目数)。
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))

输出

False
True
6
[0, 1, 3, 5, 7, 9]

Python

  1. Python 数据类型
  2. Python 运算符
  3. Python pass 语句
  4. Python 函数参数
  5. Python 迭代器
  6. Python 闭包
  7. Python 日期时间
  8. Python - 概述
  9. Python - 数字
  10. Python - 字符串
  11. Python - 元组
  12. Python - 字典