Python 字典完全指南:从入门到实战
说实话,字典是我学 Python 初期觉得最"神奇"的数据结构。学了列表之后,总觉得字典是"升级版",但真正用起来才发现,门道还挺多的。这篇文章把我踩过的坑和实战经验全部分享出来。
字典是什么
简单说,字典就是键值对(Key-Value)的集合。每个键对应一个值,像查字典一样------你知道"键",就能找到"值"。
python
# 基础字典
person = {"name": "张三", "age": 25, "city": "北京"}
print(person["name"]) # 输出: 张三
创建字典的几种方式
python
# 方式1:直接写
d1 = {"a": 1, "b": 2}
# 方式2:dict() 函数
d2 = dict(a=1, b=2) # 注意:键不能加引号
d3 = dict([("a", 1), ("b", 2)]) # 从列表创建
# 方式3:空字典
d4 = {}
d5 = dict()
# 方式4:字典推导式
d6 = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
基础操作:增删改查
查:访问值
python
person = {"name": "张三", "age": 25}
# 普通访问
print(person["name"]) # 张三
# get() 方法(推荐,更安全)
print(person.get("name")) # 张三
print(person.get("gender", "未知")) # 未知的默认值:未知
增:添加键值对
python
person = {"name": "张三", "age": 25}
# 直接添加
person["city"] = "北京"
print(person) # {'name': '张三', 'age': 25, 'city': '北京'}
# update() 合并字典
person.update({"phone": "13800138000", "age": 26}) # age 会更新,phone 新增
print(person) # {'name': '张三', 'age': 26, 'city': '北京', 'phone': '13800138000'}
改:修改值
python
person = {"name": "张三", "age": 25}
person["age"] = 26 # 直接修改
print(person["age"]) # 26
删:删除键值对
python
person = {"name": "张三", "age": 25, "city": "北京"}
# del 删除
del person["city"]
# pop() 删除并返回值
age = person.pop("age")
print(age) # 25
print(person) # {'name': '张三'}
# popitem() 删除最后一个键值对(Python 3.7+)
key, value = person.popitem()
字典的常用方法
keys()、values()、items()
python
person = {"name": "张三", "age": 25, "city": "北京"}
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['张三', 25, '北京'])
print(person.items()) # dict_items([('name', '张三'), ('age', 25), ('city', '北京')])
# 遍历
for key in person.keys():
print(key)
for value in person.values():
print(value)
for key, value in person.items():
print(f"{key}: {value}")
setdefault():安全插入
python
person = {"name": "张三", "age": 25}
# 如果键不存在才插入
person.setdefault("city", "北京") # 插入
person.setdefault("name", "李四") # 键已存在,不会覆盖
print(person) # {'name': '张三', 'age': 25, 'city': '北京'}
copy():浅拷贝
python
person = {"name": "张三", "age": 25}
person_copy = person.copy()
person_copy["name"] = "李四"
print(person["name"]) # 张三(原字典不变)
print(person_copy["name"]) # 李四
嵌套字典
字典的值可以是任何类型,包括字典本身:
python
# 嵌套字典
users = {
"user1": {"name": "张三", "scores": [90, 85, 88]},
"user2": {"name": "李四", "scores": [95, 92, 96]}
}
# 访问嵌套值
print(users["user1"]["name"]) # 张三
print(users["user2"]["scores"][0]) # 95
# 添加新用户
users["user3"] = {"name": "王五", "scores": [70, 75]}
实际应用:学生信息管理
python
students = {}
while True:
print("\n1. 添加学生 2. 查看学生 3. 查看所有 4. 退出")
choice = input("选择: ")
if choice == "1":
name = input("学生姓名: ")
score = int(input("学生成绩: "))
students[name] = {"score": score}
print(f"已添加 {name}")
elif choice == "2":
name = input("学生姓名: ")
if name in students:
print(f"{name}: {students[name]['score']}分")
else:
print("不存在")
elif choice == "3":
for name, info in students.items():
print(f"{name}: {info['score']}分")
elif choice == "4":
break
字典推导式
python
# 基础用法
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 条件过滤
numbers = {"a": 1, "b": 2, "c": 3, "d": 4}
big_ones = {k: v for k, v in numbers.items() if v > 2}
print(big_ones) # {'c': 3, 'd': 4}
# 键值互换
original = {"a": 1, "b": 2, "c": 3}
reversed_d = {v: k for k, v in original.items()}
print(reversed_d) # {1: 'a', 2: 'b', 3: 'c'}
实战案例
案例1:单词计数器
python
text = "python is great and python is easy to learn python"
words = text.split()
# 统计每个单词出现次数
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
# {'python': 3, 'is': 2, 'great': 1, 'and': 1, 'easy': 1, 'to': 1, 'learn': 1}
# 更简洁的方式:用 defaultdict
from collections import defaultdict
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
print(dict(word_count))
案例2:合并两个字典
python
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
# 方法1:update(会修改原字典)
merged = dict1.copy()
merged.update(dict2)
print(merged) # {'a': 1, 'b': 3, 'c': 4} 注意:b 被覆盖了
# 方法2:解包(Python 3.9+,不会覆盖)
merged2 = {**dict1, **dict2}
print(merged2) # {'a': 1, 'b': 3, 'c': 4}
# 方法3:dict | dict(Python 3.9+)
merged3 = dict1 | dict2
print(merged3) # {'a': 1, 'b': 3, 'c': 4}
案例3:从列表创建字典
python
# 场景:名字列表转字典(默认值为0)
names = ["张三", "李四", "王五"]
name_dict = {name: 0 for name in names}
print(name_dict) # {'张三': 0, '李四': 0, '王五': 0}
# 场景:两个列表配对
keys = ["name", "age", "city"]
values = ["张三", 25, "北京"]
info_dict = dict(zip(keys, values))
print(info_dict) # {'name': '张三', 'age': 25, 'city': '北京'}
我踩过的坑
坑1:键不存在时报错
python
person = {"name": "张三"}
# 这会报错!
# print(person["age"]) # KeyError: 'age'
# 正确做法:用 get()
print(person.get("age", 0)) # 0
坑2:字典是无序的(旧版本)
python
# Python 3.7+ 字典是有序的
d = {"a": 1, "b": 2, "c": 3}
print(d) # 按插入顺序输出
# 但如果你需要有序字典
from collections import OrderedDict
od = OrderedDict()
坑3:字典的键必须是不可变类型
python
# 可以:字符串、数字、元组
d1 = {"name": "张三"}
d2 = {1: "one", 2: "two"}
d3 = {(1, 2): "point"}
# 不可以:列表、字典
# d4 = {[1, 2]: "list"} # TypeError
写在最后
字典是 Python 里最强大的数据结构之一,用熟了真的能大大简化代码。我的经验是:大部分需要快速查找的场景,字典都是首选。
有问题评论区见!