Python [dictionary]
Dictionaries are another model of mutable containers that can store objects of any type.
Each key-value key->value
pair of a dictionary is separated by a colon, each pair is separated by a comma, and the entire dictionary is enclosed in curly braces, in the following format:
d = {
2:123,1:10}
print(d[2])
print(d[1])
d[2] = 100
print(d[2])
output:
123
10
100
Use built-in functions to create dictionaries:
d = dict() # 创建字典
print(d) # 打印字典,此时为空
print(len(d)) # 打印字典的键值对数量
print(type(d)) # 查看d的类型
output:
{}
0
<class 'dict'>
modify, add, delete
d = dict() # 创建字典
d[1] = 10 # 添加元素
d[2] = 50 # 添加元素
print(d)
d[1] = 20 # 修改元素
print(d)
del d[1] # 删除键1
print(d)
d.clear() # 清空字典
print(d)
del d # 删除字典
output:
{1: 10, 2: 50}
{1: 20, 2: 50}
{2: 50}
{}
Commonly used built-in functions for dictionaries
d = dict() # 创建字典
d[1] = 10 # 添加元素
d[2] = 50 # 添加元素
print(len(d)) # 查看字典的元素个数
print(1 in d) # 查看键1是否在d中
print(3 in d) # 查看键3是否在d中
x = d.copy() # 将d的内容复制给x
del x[1] # 对x的操作不会影响d
print(x)
print(d)
output:
2
True
False
{2: 50}
{1: 10, 2: 50}