第五章第2讲:字典的方法(1)
第2讲:字典的方法(1)
1. clear方法:清空所有字典(原有内存),无返回值
# 字典的clear方法 x = {} y = x x["key"] = "value" print(x) print(y) x = {} print(x) print(y) print("====字典的clear方法===") x1 = {} y1 = x1 print(x1) print(y1) x1["Alice"] = "010-12345678" print(x1) print(y1) x1.clear() print(x1) print(y1) 结果: {'key': 'value'} {'key': 'value'} {} {'key': 'value'} ====字典的clear方法=== {} {} {'Alice': '010-12345678'} {'Alice': '010-12345678'} {} {}
2. copy方法(浅复制):替换值,原字典不变;修改(增加或删除)某个键的值,原字典一并变化
student_info = {"Alice":"1234","Bob":["5555","Boy"]} print(student_info) copy_student_info= student_info.copy() print(copy_student_info) # 针对copy后新字典,修改键的值,原字典不会受影响 copy_student_info["Alice"] = "3333" print(copy_student_info) print(student_info) print("=======copy后新字典的增加或删除键=======") # 当对copy的新字典增加或删除时,会原字典有影响 copy_student_info["Bob"].remove("5555") print(copy_student_info) print(student_info) print("=====针对copy的字典删除某个键,原字典不受影响======") del copy_student_info["Alice"] print(copy_student_info) print(student_info) 结果: {'Alice': '1234', 'Bob': ['5555', 'Boy']} {'Alice': '1234', 'Bob': ['5555', 'Boy']} {'Alice': '3333', 'Bob': ['5555', 'Boy']} {'Alice': '1234', 'Bob': ['5555', 'Boy']} =======copy后新字典的增加或删除键======= {'Alice': '3333', 'Bob': ['Boy']} {'Alice': '1234', 'Bob': ['Boy']} =====针对copy的字典删除某个键,原字典不受影响====== {'Bob': ['Boy']} {'Alice': '1234', 'Bob': ['Boy']}