python的字典
柠栀 2025/9/24 python
# 1.字典是什么?
字典 是一个无序、可变的容器,存储键值对的集合。
- 键值对:每个元素都由一个键(key)和一个值(value)组成,格式为
key: value - 无序:在 Python 3.7+ 中,字典会保持插入顺序,但从概念上讲仍是无序集合
- 可变:可以添加、删除、修改键值对
- 键的要求:键必须是不可变类型(字符串、数字、元组等),且不能重复
- 值的要求:值可以是任意类型,可以重复
核心特性:通过键来快速访问值,就像现实中的字典通过单词查解释一样。
# 2.创建字典
有多种方式创建字典:
# 2.1.1. 使用花括号 {}
# 空字典
empty_dict = {}
print(empty_dict) # {}
# 包含键值对的字典
person = {
"name": "Alice",
"age": 30,
"city": "Beijing"
}
scores = {
"math": 95,
"english": 88,
"science": 92
}
print(person) # {'name': 'Alice', 'age': 30, 'city': 'Beijing'}
print(scores) # {'math': 95, 'english': 88, 'science': 92}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 2.2.使用 dict()
dict()是内置的构造函数,可以通过多种方式创建字典。
- 从一组键值对的序列(如列表元组)创建
- 使用关键字参数(键必须是合法的标识符——通常用于英文键)
- 从可迭代对象,元素为二元组
- 从已知的键和相同的默认值,利用
.fromkeys()
# 从键值对序列创建
dict1 = dict([("name", "Bob"), ("age", 25), ("city", "Shanghai")])
print(dict1) # {'name': 'Bob', 'age': 25, 'city': 'Shanghai'}
# 使用关键字参数(键必须是有效的变量名)
dict2 = dict(name="Charlie", age=35, city="Guangzhou")
print(dict2) # {'name': 'Charlie', 'age': 35, 'city': 'Guangzhou'}
# 从包含双元素子序列的可迭代对象创建
dict3 = dict([["a", 1], ["b", 2]])
print(dict3) # {'a': 1, 'b': 2}
# 使用 fromkeys() 创建字典:所有键的值默认相同
keys = ["math", "english", "science"]
default_score = 60
score_dict = dict.fromkeys(keys, default_score)
print(score_dict) # {'math': 60, 'english': 60, 'science': 60}
# 如果不指定默认值,默认是 None
empty_dict = dict.fromkeys(keys)
print(empty_dict) # {'math': None, 'english': None, 'science': None}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 2.3.字典推导式
字典推导式(dict comprehension)用类似列表推导式的语法,快速批量生成字典。
基本语法:{key_expr: value_expr for 变量 in 可迭代对象 [if 条件]}
# 创建数字平方的字典
squares = {x: x ** 2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 带条件的字典推导式
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# 转换现有字典
original = {"a": 1, "b": 2, "c": 3}
doubled = {k: v * 2 for k, v in original.items()}
print(doubled) # {'a': 2, 'b': 4, 'c': 6}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 3.访问字典元素
# 3.1.通过键直接访问
person = {"name": "Alice", "age": 30, "city": "Beijing"}
print(person["name"]) # "Alice"
print(person["age"]) # 30
# 如果键不存在,会报 KeyError
# print(person["country"]) # KeyError: 'country'
1
2
3
4
5
6
7
2
3
4
5
6
7
# 3.2.使用 get() 方法
更安全的方式,键不存在时返回 None 或指定的默认值。
person = {"name": "Alice", "age": 30, "city": "Beijing"}
print(person.get("name")) # "Alice"
print(person.get("country")) # None (不会报错)
print(person.get("country", "Unknown")) # "Unknown" (指定默认值)
1
2
3
4
5
2
3
4
5
# 3.3.使用 setdefault() 方法
如果键存在则返回值,如果不存在则设置键值对并返回值。
person = {"name": "Alice", "age": 30}
# 键存在,返回对应的值
name = person.setdefault("name", "Unknown")
print(name) # "Alice"
print(person) # {'name': 'Alice', 'age': 30}
# 键不存在,设置键值对并返回值
country = person.setdefault("country", "China")
print(country) # "China"
print(person) # {'name': 'Alice', 'age': 30, 'country': 'China'}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 4.修改字典
# 4.1.添加/修改元素
person = {"name": "Alice", "age": 30}
# 修改已存在的键
person["age"] = 31
print(person) # {'name': 'Alice', 'age': 31}
# 添加新的键值对
person["city"] = "Beijing"
person["job"] = "Engineer"
print(person) # {'name': 'Alice', 'age': 31, 'city': 'Beijing', 'job': 'Engineer'}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 4.2.使用 update() 方法
批量添加或修改键值对:
person = {"name": "Alice", "age": 30}
# 使用另一个字典更新
person.update({"age": 31, "city": "Beijing"})
print(person) # {'name': 'Alice', 'age': 31, 'city': 'Beijing'}
# 使用键值对序列更新
person.update([("job", "Engineer"), ("country", "China")])
print(person) # 添加了 job 和 country
# 使用关键字参数更新
person.update(salary=50000, department="IT")
print(person) # 添加了 salary 和 department
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 5.删除元素
del语句:根据键删除对应的键值对。如果键不存在会报错。pop(key[, default])方法:删除指定键并返回对应的值。如果键不存在且没有设置 default,会报错。popitem()方法:删除并返回最后插入的键值对(Python 3.7+)。如果字典为空会报错。clear()方法:移除字典中的所有元素,变成一个空字典。del dict:删除整个字典对象,变量名不再可用。
删除元素时请注意:如果你不确定键是否存在,可以使用 pop(key, default) 方式以避免 KeyError。
person = {"name": "Alice", "age": 30, "city": "Beijing", "job": "Engineer"}
# del 语句 - 删除指定键
del person["age"]
print(person) # {'name': 'Alice', 'city': 'Beijing', 'job': 'Engineer'}
# pop() - 删除并返回指定键的值
city = person.pop("city")
print(city) # "Beijing"
print(person) # {'name': 'Alice', 'job': 'Engineer'}
# popitem() - 删除并返回最后一个键值对(Python 3.7+ 按插入顺序)
last_item = person.popitem()
print(last_item) # ('job', 'Engineer')
print(person) # {'name': 'Alice'}
# clear() - 清空字典
person.clear()
print(person) # {}
# del 删除整个字典
del person
# print(person) # NameError: name 'person' is not defined
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 6.字典遍历
# 6.1.遍历所有键
person = {"name": "Alice", "age": 30, "city": "Beijing"}
# 方法1: 直接遍历字典(默认遍历键)
for key in person:
print(key)
# 方法2: 使用 keys() 方法
for key in person.keys():
print(f"Key: {key}")
# 输出:
# name
# age
# city
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 6.2.遍历所有值
person = {"name": "Alice", "age": 30, "city": "Beijing"}
for value in person.values():
print(f"Value: {value}")
# 输出:
# Value: Alice
# Value: 30
# Value: Beijing
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 6.3.遍历所有键值对
person = {"name": "Alice", "age": 30, "city": "Beijing"}
for key, value in person.items():
print(f"{key}: {value}")
# 输出:
# name: Alice
# age: 30
# city: Beijing
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 7.字典视图对象
keys(), values(), items() 返回的是视图对象,它们会动态反映字典的变化:
person = {"name": "Alice", "age": 30}
# 创建视图对象
keys_view = person.keys()
values_view = person.values()
items_view = person.items()
print(keys_view) # dict_keys(['name', 'age'])
print(values_view) # dict_values(['Alice', 30])
print(items_view) # dict_items([('name', 'Alice'), ('age', 30)])
# 修改原字典
person["city"] = "Beijing"
# 视图对象会自动更新
print(keys_view) # dict_keys(['name', 'age', 'city'])
print(values_view) # dict_values(['Alice', 30, 'Beijing'])
print(items_view) # dict_items([('name', 'Alice'), ('age', 30), ('city', 'Beijing')])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 8.字典的常用方法
person = {"name": "Alice", "age": 30, "city": "Beijing"}
# 1. 检查键是否存在
print("name" in person) # True
print("country" in person) # False
# 2. 获取字典长度(键值对数量)
print(len(person)) # 3
# 3. 复制字典
person_copy = person.copy()
print(person_copy) # {'name': 'Alice', 'age': 30, 'city': 'Beijing'}
# 4. 创建新字典(fromkeys)
# 从序列创建键,所有键的值相同
new_dict = dict.fromkeys(["a", "b", "c"], 0)
print(new_dict) # {'a': 0, 'b': 0, 'c': 0}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 9.嵌套字典
字典的值可以是任何类型,包括另一个字典:
# 嵌套字典示例:学生信息系统
students = {
"student1": {
"name": "Alice",
"age": 20,
"grades": {
"math": 95,
"english": 88,
"science": 92
}
},
"student2": {
"name": "Bob",
"age": 21,
"grades": {
"math": 85,
"english": 90,
"science": 78
}
}
}
# 访问嵌套数据
print(students["student1"]["name"]) # "Alice"
print(students["student1"]["grades"]["math"]) # 95
# 修改嵌套数据
students["student2"]["grades"]["science"] = 85
# 添加新学生
students["student3"] = {
"name": "Charlie",
"age": 22,
"grades": {
"math": 92,
"english": 85,
"science": 95
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 10.字典的典型应用场景
# 10.1.配置信息存储
# 应用配置
app_config = {
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp_db"
},
"server": {
"host": "0.0.0.0",
"port": 8000,
"debug": True
},
"features": {
"cache": True,
"logging": True
}
}
# 访问配置
db_host = app_config["database"]["host"]
server_port = app_config["server"]["port"]
print(f"数据库: {db_host}:{app_config['database']['port']}") # 数据库: localhost:5432
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 10.2.数据分组和统计
# 统计单词频率
text = "apple banana apple orange banana apple"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # {'apple': 3, 'banana': 2, 'orange': 1}
# 使用 collections.Counter 更简单
from collections import Counter
word_count = Counter(words)
print(word_count) # Counter({'apple': 3, 'banana': 2, 'orange': 1})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 10.3.快速查找表
# 颜色名称到十六进制值的映射
color_map = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF",
"white": "#FFFFFF",
"black": "#000000"
}
def get_color_hex(color_name):
return color_map.get(color_name.lower(), "#000000")
print(get_color_hex("red")) # #FF0000
print(get_color_hex("yellow")) # #000000 (默认黑色)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 11.字典 vs 其他数据结构
| 特性 | 列表 (List) | 元组 (Tuple) | 集合 (Set) | 字典 (Dict) |
|---|---|---|---|---|
| 语法 | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {"a": 1, "b": 2} |
| 元素结构 | 单个元素 | 单个元素 | 单个元素 | 键值对 |
| 有序性 | 有序 | 有序 | 无序 | 保持插入顺序 |
| 可变性 | 可变 | 不可变 | 可变 | 可变 |
| 键要求 | 无索引概念 | 无索引概念 | 元素需不可变 | 键需不可变 |
| 主要用途 | 有序序列 | 不可变序列 | 唯一元素、集合运算 | 键值映射、快速查找 |
# 12.选择指南:
- 使用字典:当数据有自然的键值对关系,需要通过键快速查找值时
- 使用列表:需要有序集合,通过位置访问元素
- 使用元组:需要不可变的有序集合
- 使用集合:需要存储唯一元素,或进行集合运算
记住:字典是 Python 的"万能工具",当你需要将一组信息关联起来时,字典通常是最佳选择!
# 13.高级技巧
# 13.1.使用 collections 模块的特殊字典
from collections import defaultdict, OrderedDict
# defaultdict - 为不存在的键提供默认值
word_count = defaultdict(int) # 默认值为0
word_count["apple"] += 1
print(word_count["apple"]) # 1
print(word_count["banana"]) # 0 (不会报错)
# OrderedDict - 保持插入顺序(Python 3.7+ 普通字典已支持)
ordered = OrderedDict()
ordered["a"] = 1
ordered["b"] = 2
ordered["c"] = 3
print(list(ordered.keys())) # ['a', 'b', 'c']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 13.2.字典合并(Python 3.9+)
字典合并是指将两个或多个字典合并为一个新字典,在 Python 3.9 及以上,可以直接使用 | 运算符来实现
如果需要原地更新(修改原字典),可以使用 |= 运算符:
# Python 3.9+ 支持 | 运算符合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2 # 后者覆盖前者
print(merged) # {'a': 1, 'b': 3, 'c': 4}
# 原地更新
dict1 |= dict2
print(dict1) # {'a': 1, 'b': 3, 'c': 4}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
注意:如果你的 Python 版本低于 3.9,可以使用
update()方法或字典解包{**dict1, **dict2}实现类似效果,但推荐升级到新版本,享受更简单直观的语法。