创建
- key不可改,不重复(若重复,最后一个生效)
- key可以是字符串,数字,元组
- .fromkeys()新创建字典以其中元素为key,其后跟值,不改变原字典中的值
z_c0 = {}
z_c1 = {1:"we", "er":12, (1, 2):(4, 5)}
print(z_c0)
print(z_c1)
z_c2 = {1:3, "we":7}
z_c3 = [1, "ty", (1, 4)]
print(id(z_c2))
print(id(z_c2.fromkeys(z_c3)))
print(z_c2.fromkeys(z_c3)) #创建字典z_c2,以z_c3为key,全部赋值None
print(z_c2.fromkeys(z_c3, 10)) #创建字典z_c2,以z_c3为key,全部赋值10
print(z_c2) #不改变z_c2值
访问
z_f0 = {1:1, "h":"qw", 5:5}
print(z_f0["h"])
增
z_z0 = {1:"we", 9:0}
z_z0[8] = "tot"
print(z_z0)
.copy()
- 直接赋值:完全都是浅拷贝
- 一级结构都是深拷贝,但是值中有二级结构的话,其中的二级结构是浅拷贝
z_z1 = {1:1, 2:2, 3:{1,2,3}}
z_z2 = z_z1
z_z3 = z_z1.copy()
z_z1[1] = 89
z_z1[2] = 90
z_z1[3].remove(1)
print(z_z1)
print(z_z2)
print(z_z3)
.update()
z_z4 = {1:1, 2:2}
z_z5 = {3:3, 4:("we", "er")}
z_z4.update(z_z5)
print(z_z4)
删除
del dict[key]
del dict
dict.clear()
.pop()
- 删除字典给定键key和所对应的值,返回值为被删除的值。key值必须给出。否则,返回预设值
z_s0 = {1:1, 2:2, 3:3}
print(z_s0.pop(1, 10))
print(z_s0)
print(z_s0.pop(5, 10))
print(z_s0)
.popitem()
z_s1 = {1:1, 2:2, 3:3}
print(z_s1.popitem())
print(z_s1)
查询
.items()
z_x0 = {1:10, 2:20, 3:30}
print(z_x0.items())
print(list(z_x0.items()))
.keys()
print(z_x0.keys())
print(list(z_x0.keys()))
.values()
print(z_x0.values())
print(list(z_x0.values()))
.get()
- 访问字典中的不存在的key,不会报错,并返回预设好的值
print(z_x0.get(6, None))
.setdefaule()
- 访问字典中的存在的key是正常访问,若不存在,不报错,并创建此key以预设值填充
print(z_x0.setdefault(1))
print(z_x0.setdefault(10, "阿"))
print(z_x0)