Python 字典详解
1. 字典基础
什么是字典?
字典是Python中一种可变、无序的键值对集合。每个键值对用冒号分隔,键值对之间用逗号分隔,整个字典包括在花括号 {} 中。
python
# 创建字典
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# 访问值
print(person["name"]) # 输出: Alice
print(person.get("age")) # 输出: 25
字典的特点
- 键必须是不可变类型(字符串、数字、元组)
- 键必须是唯一的
- 值可以是任意类型
- 无序(Python 3.7+ 保持了插入顺序)
2. 创建字典的方法
python
# 方法1: 直接创建
dict1 = {"name": "Alice", "age": 25}
# 方法2: 使用 dict() 构造函数
dict2 = dict(name="Bob", age=30)
# 方法3: 从键值对列表创建
dict3 = dict([("name", "Charlie"), ("age", 35)])
# 方法4: 使用字典推导式
dict4 = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 方法5: 使用 fromkeys() 创建默认值字典
keys = ["name", "age", "city"]
dict5 = dict.fromkeys(keys, None) # {'name': None, 'age': None, 'city': None}
3. 常用字典操作
访问元素
python
person = {"name": "Alice", "age": 25}
# 使用键访问
print(person["name"]) # Alice
# 使用 get() 方法(避免 KeyError)
print(person.get("age")) # 25
print(person.get("height", "Not found")) # 默认值: Not found
# 检查键是否存在
print("name" in person) # True
print("height" in person) # False
添加和修改元素
python
person = {"name": "Alice"}
# 添加新键值对
person["age"] = 25
person["city"] = "New York"
# 修改值
person["age"] = 26
# 使用 update() 方法
person.update({"job": "Engineer", "age": 27})
删除元素
python
person = {"name": "Alice", "age": 25, "city": "NY"}
# 删除指定键
del person["city"]
# 使用 pop() 删除并返回值
age = person.pop("age") # 返回 25
# 使用 popitem() 删除最后一个键值对(Python 3.7+)
item = person.popitem() # 返回 ('name', 'Alice')
# 清空字典
person.clear()
# 删除整个字典
del person
4. 字典遍历
python
student = {
"name": "Alice",
"age": 22,
"major": "Computer Science",
"grades": {"math": 90, "english": 85}
}
# 遍历键
for key in student:
print(key)
# 遍历键(显式)
for key in student.keys():
print(key)
# 遍历值
for value in student.values():
print(value)
# 遍历键值对
for key, value in student.items():
print(f"{key}: {value}")
# 遍历嵌套字典
for subject, grade in student["grades"].items():
print(f"{subject}: {grade}")
5. 字典方法
python
person = {"name": "Alice", "age": 25, "city": "NY"}
# keys() - 返回所有键
print(list(person.keys())) # ['name', 'age', 'city']
# values() - 返回所有值
print(list(person.values())) # ['Alice', 25, 'NY']
# items() - 返回所有键值对
print(list(person.items())) # [('name', 'Alice'), ('age', 25), ('city', 'NY')]
# get() - 安全获取值
print(person.get("height", 170)) # 170
# setdefault() - 获取值,如果不存在则设置默认值
person.setdefault("country", "USA")
# copy() - 创建浅拷贝
person_copy = person.copy()
# fromkeys() - 从序列创建字典
new_dict = dict.fromkeys(["a", "b", "c"], 0) # {'a': 0, 'b': 0, 'c': 0}
6. 字典推导式
python
# 基本推导式
squares = {x: x**2 for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 带条件的推导式
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# 转换现有字典
original = {"a": 1, "b": 2, "c": 3}
doubled = {k: v*2 for k, v in original.items()}
# 交换键值
swapped = {v: k for k, v in original.items()}
7. 嵌套字典
python
# 嵌套字典示例
students = {
"001": {
"name": "Alice",
"age": 22,
"grades": {"math": 90, "english": 85}
},
"002": {
"name": "Bob",
"age": 23,
"grades": {"math": 78, "english": 92}
}
}
# 访问嵌套值
print(students["001"]["name"]) # Alice
print(students["002"]["grades"]["math"]) # 78
# 修改嵌套值
students["001"]["age"] = 23
students["001"]["grades"]["history"] = 88
8. 字典排序
python
# Python 3.7+ 字典保持插入顺序,但有时需要排序
scores = {"Charlie": 85, "Alice": 95, "Bob": 90}
# 按键排序
sorted_by_key = dict(sorted(scores.items()))
# {'Alice': 95, 'Bob': 90, 'Charlie': 85}
# 按值排序
sorted_by_value = dict(sorted(scores.items(), key=lambda item: item[1]))
# {'Charlie': 85, 'Bob': 90, 'Alice': 95}
# 按值降序排序
sorted_by_value_desc = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))
9. 字典合并
python
# Python 3.5+ 使用 ** 运算符
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2} # {'a': 1, 'b': 3, 'c': 4}
# Python 3.9+ 使用 | 运算符
merged = dict1 | dict2 # {'a': 1, 'b': 3, 'c': 4}
# 使用 update() 方法
dict1.update(dict2) # dict1 被修改
# 使用字典推导式
merged = {k: v for d in [dict1, dict2] for k, v in d.items()}
10. 实用示例
python
# 示例1: 单词频率统计
def word_frequency(text):
words = text.lower().split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
return frequency
text = "apple banana apple orange banana apple"
print(word_frequency(text)) # {'apple': 3, 'banana': 2, 'orange': 1}
# 示例2: 配置管理
config = {
"database": {
"host": "localhost",
"port": 5432,
"name": "mydb"
},
"server": {
"host": "0.0.0.0",
"port": 8000
}
}
# 示例3: 缓存实现
class SimpleCache:
def __init__(self, max_size=100):
self.cache = {}
self.max_size = max_size
def get(self, key):
return self.cache.get(key)
def set(self, key, value):
if len(self.cache) >= self.max_size:
self.cache.pop(next(iter(self.cache)))
self.cache[key] = value
11. 注意事项
python
# 1. 键必须是不可变类型
# 正确的键
valid_keys = {
"string": "value",
123: "value",
(1, 2, 3): "value"
}
# 错误的键(列表不能作为键)
# invalid = {[1, 2]: "value"} # TypeError
# 2. 避免在遍历时修改字典
data = {"a": 1, "b": 2, "c": 3}
# for key in data:
# if key == "b":
# del data[key] # RuntimeError
# 正确的做法
keys_to_remove = []
for key in data:
if key == "b":
keys_to_remove.append(key)
for key in keys_to_remove:
del data[key]
# 3. 使用 defaultdict 处理缺失键
from collections import defaultdict
word_count = defaultdict(int) # 默认值为0
word_count["apple"] += 1 # 不需要检查键是否存在
总结
Python字典是一种非常高效和灵活的数据结构,特别适合存储和查询键值对数据。掌握字典的各种操作和方法,能够大大提高编程效率。字典在Python中的应用非常广泛,从简单的数据存储到复杂的算法实现都离不开它。