第五章第3讲:字典的方法(2)
3.deepcopy函数:深度复制,可以理解为与原字典是两个不同的字典,它们之间没有任何关系
# 字典下deepcopy函数 from copy import deepcopy d = {} d["names"] = ["Alice","Bob"] print("d:",d) print("=====字典copy(浅复制)的回顾=====") b = d.copy() # b是d的浅复制 # 浅复制,针对copy后的字典,修改了键的值,原字典不受影响 b["names"] = ["Bela"] b["age"] = "20" print("b:",b) print("d:",d) # 浅复制,针对copy后的字典,删除了某键的值,原字典受影响 b["names"].remove("Bela") print("d:",d) print("b:",b) print("====字典deepcopy函数=====") # deepcopy 深度复制,理解为完全复制一个新的字典(对象)与原字典不再有任何关系 # 对deepcopy后的字典,进行任何操作,都不会对原字典有影响 dc = deepcopy(d) dc["sex"] = "Boy" dc["names"].remove("Alice") print("dc:",dc) print("d:",d) 结果: d: {'names': ['Alice', 'Bob']} =====字典copy(浅复制)的回顾===== b: {'names': ['Bela'], 'age': '20'} d: {'names': ['Alice', 'Bob']} d: {'names': ['Alice', 'Bob']} b: {'names': [], 'age': '20'} ====字典deepcopy函数===== dc: {'names': ['Bob'], 'sex': 'Boy'} d: {'names': ['Alice', 'Bob']}
4.get方法:获取字典项的方法
d = {"name":"Bob"} print(d) print(d["name"]) # 输出字典中的存在的键 # print(d["age"]) # 由于age键不存在,会报错 print(d.get("age","no value or key")) print(d.get("name","no value or key")) 结果: {'name': 'Bob'} Bob no value or key Bob
5.key方法:将字典的键以列表形式返回
PeoplePhone = { "Alice":{ "phone":"1234", "tel":"12345678" }, "Bob":{ "phone": "2234", "tel":"22345678" }, "Bela": { "phone": "3234", "tel":"22345678" } } print(PeoplePhone.keys()) 结果: dict_keys(['Alice', 'Bob', 'Bela'])
6.pop方法:获取给定键的值,同时把该键的也删除
student_info = {"Alice":42,"Bob":45} b = student_info.pop("Alice") print(b) print(student_info) 结果: 42 {'Bob': 45}
7.popitem方法:随机弹出键
student_info = {"Alice":42,"Bob":45,"Bela":50} student_info.popitem() print(student_info) 结果: {'Alice': 42, 'Bob': 45}
8.setdefault方法:与get类似,能够获取给定键相关联的值,还能在字典中不含有给定键的值的情况下设定相应的键值
d = {}
d.setdefault("name","Bela")
print(d)
c = d.setdefault("name")
print(c)
结果:
{'name': 'Bela'}
Bela
9. update方法:利用另一个字典,更新现有字典
tudent_info = {"Alice":42,"Bob":45} Bela_info = {"Bela":50} student_info.update(Bela_info) print(student_info) tom_info = {"Tome":99} student_info.update(tom_info) print(student_info) 结果: {'Alice': 42, 'Bob': 45, 'Bela': 50} {'Alice': 42, 'Bob': 45, 'Bela': 50, 'Tome': 99}