一、核心特性
✅ 可变对象:内容可动态修改
✅ 键唯一性:重复键会覆盖旧值
✅ 键不可变:键必须是可哈希类型(str, int, tuple等)
✅ 值任意类型:可存储数字、列表、函数甚至其他字典
✅ 有序性:Python 3.7+ 保证插入顺序(非排序)
二、创建字典
1. 使用花括号创建
①. 创建空字典empty_dict = {}print(empty_dict) # {}②. 创建有初始值的字典person = { "name": "张三", "age": 25, "city": "北京"}print(person) # {'name': '张三', 'age': 25, 'city': '北京'}
2. 使用dict()构造函数
方式1:使用关键字参数dict1 = dict(name="李四", age=30)print(dict1) # {'name': '李四', 'age': 30}方式2:使用键值对列表dict2 = dict([("name", "王五"), ("age", 28)])print(dict2) # {'name': '王五', 'age': 28}方式3:使用可迭代对象dict3 = dict(zip(["name", "age"], ["赵六", 32]))print(dict3) # {'name': '赵六', 'age': 32}
3. 使用字典推导式
创建键为数字,值为平方的字典:squares = {x: x**2 for x in range(1, 6)}print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
三、访问字典元素
1. 使用键访问
student = {"name": "小明", "score": 90, "grade": "A"}①. 直接使用键访问print(student["name"]) # 小明②. 使用get()方法(更安全,键不存在时返回None或默认值)print(student.get("name")) # 小明print(student.get("age")) # Noneprint(student.get("age", 0)) # 0(设置默认值)
2. 检查键是否存在
if "name" in student: print(f"姓名: {student['name']}") # 姓名: 小明if "age" not in student: print("年龄信息不存在") # 年龄信息不存在
四、修改字典
1. 添加或修改元素
①. 添加新键值对student["age"] = 18print(student) # {'name': '小明', 'score': 90, 'grade': 'A', 'age': 18}②. 修改已有键的值student["score"] = 95print(student) # {'name': '小明', 'score': 95, 'grade': 'A', 'age': 18}③. 使用update()合并字典student.update({"age": 19, "class": "三年二班"})print(student) # {'name': '小明', 'score': 95, 'grade': 'A', 'age': 19, 'class': '三年二班'}
2. 删除元素
①. 使用del语句del student["grade"]print(student) # {'name': '小明', 'score': 95, 'age': 19, 'class': '三年二班'}②. 使用pop()方法(返回被删除的值)score = student.pop("score")print(score) # 95print(student) # {'name': '小明', 'age': 19, 'class': '三年二班'}③. 使用popitem()删除最后插入的键值对(Python 3.7+有序)last_item = student.popitem()print(last_item) # ('class', '三年二班')print(student) # {'name': '小明', 'age': 19}④. 清空字典student.clear()print(student) # {}
五、遍历字典
book = { "title": "Python编程", "author": "John Doe", "year": 2023, "price": 59.9}①. 遍历所有键print("所有键:")for key in book.keys(): print(f"- {key}")# 输出:# - title# - author# - year# - price②. 遍历所有值print("\n所有值:")for value in book.values(): print(f"- {value}")# 输出:# - Python编程# - John Doe# - 2023# - 59.9③. 遍历所有键值对print("\n所有键值对:")for key, value in book.items(): print(f"{key}: {value}")# 输出:# title: Python编程# author: John Doe# year: 2023# price: 59.9
六、字典常用方法
1. setdefault() - 安全设置默认值data = {"a": 1, "b": 2}①. 键不存在时设置默认值value = data.setdefault("c", 3)print(value) # 3print(data) # {'a': 1, 'b': 2, 'c': 3}②. 键存在时返回现有值value = data.setdefault("a", 100)print(value) # 1(保持原值不变)
2. fromkeys() - 从序列创建字典
①. 创建具有相同默认值的字典keys = ["name", "age", "city"]default_dict = dict.fromkeys(keys, "未知")print(default_dict) # {'name': '未知', 'age': '未知', 'city': '未知'}②. 使用不同的默认值class DefaultFactory: def __init__(self): self.counter = 0 def __call__(self): self.counter += 1 return f"值{self.counter}"factory = DefaultFactory()dynamic_dict = dict.fromkeys(keys, factory())print(dynamic_dict) # {'name': '值1', 'age': '值1', 'city': '值1'}
3. copy() - 创建浅拷贝
original = {"a": 1, "b": [2, 3, 4]}copied = original.copy()original["a"] = 10original["b"].append(5)print(original) # {'a': 10, 'b': [2, 3, 4, 5]}print(copied) # {'a': 1, 'b': [2, 3, 4, 5]} # 注意:列表是浅拷贝
七、嵌套字典
①. 创建嵌套字典school = { "class1": { "teacher": "王老师", "students": ["张三", "李四", "王五"], "score": {"数学": 85, "语文": 90} }, "class2": { "teacher": "张老师", "students": ["赵六", "孙七"], "score": {"数学": 88, "语文": 92} }}②. 访问嵌套字典print(school["class1"]["teacher"]) # 王老师print(school["class1"]["students"][0]) # 张三print(school["class1"]["score"]["数学"]) # 85③. 修改嵌套字典school["class1"]["students"].append("周八")school["class1"]["score"]["英语"] = 88
八、字典视图对象
Python 3中的keys()、values()和items()返回的是视图对象,它们会动态反映字典的变化:
d = {"a": 1, "b": 2, "c": 3}keys_view = d.keys()values_view = d.values()items_view = d.items()print(list(keys_view)) # ['a', 'b', 'c']print(list(values_view)) # [1, 2, 3]# 修改字典d["d"] = 4d["a"] = 100# 视图对象会动态更新print(list(keys_view)) # ['a', 'b', 'c', 'd']print(list(values_view)) # [100, 2, 3, 4]print(list(items_view)) # [('a', 100), ('b', 2), ('c', 3), ('d', 4)]
九、字典合并(Python 3.9+)
①. Python 3.9+ 使用 | 运算符合并字典dict1 = {"a": 1, "b": 2}dict2 = {"b": 3, "c": 4}②. 合并字典,后者优先级高merged = dict1 | dict2print(merged) # {'a': 1, 'b': 3, 'c': 4}③. 原地合并dict1 |= dict2print(dict1) # {'a': 1, 'b': 3, 'c': 4}
十、遍历技巧(顺序验证)
info = {'city': 'Beijing', 'pop': 2100}①. 遍历键(推荐)for k in info: print(k) # city → pop ✅(保持插入顺序)②. 遍历键值对for k, v in info.items(): print(f"{k}: {v}") # city: Beijing# pop: 2100 ✅
十一、避坑指南
| | |
|---|
| d = {[1]:1} | d = {(1,):1} |
| d2 = d1; d2['x']=0 | d2 = d1.copy() |
| for k in d: del d[k] | 先转列表:for k in list(d): ... ✅ |
✅浅拷贝验证:
original = {'data': [1,2]}shallow = original.copy()shallow['data'].append(3)print(original) # {'data': [1, 2, 3]} → 内部列表被共享!
十二、总结与最佳实践