Python 字典(Dictionary)详解
在 Python 中,字典(Dictionary)是一种键值对(key-value) 结构的可变容器,类似于 Java 中的 Map 或 JavaScript 中的对象。它通过键(key)快速查找对应的值(value),是处理关联数据的核心数据结构。本文将详细介绍字典的创建、操作及常用方法。
字典的基本定义
字典使用大括号 {} 定义,键值对之间用逗号分隔,键与值用冒号 : 连接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| student = {'name': 'Alice', 'age': 20, 'major': 'Computer Science'}
mixed_dict = { 1: 'one', ('a', 'b'): 123, 'list': [1, 2, 3] }
empty_dict = {}
another_dict = dict(name='Bob', age=21)
|
注意:
- 键必须是不可变类型(如字符串、整数、元组),列表等可变类型不能作为键。
- 键是唯一的,若重复定义,后面的键值对会覆盖前面的。
字典的核心操作
访问值(通过键)
通过 字典名[键] 访问对应的值,若键不存在则报错。
1 2 3 4 5 6 7
| student = {'name': 'Alice', 'age': 20}
print(student['name']) print(student['age'])
print(student.get('major', 'Unknown'))
|
添加 / 修改键值对
- 若键不存在,赋值操作会添加新的键值对。
- 若键已存在,赋值操作会修改对应的值。
1 2 3 4 5 6 7 8 9
| student = {'name': 'Alice', 'age': 20}
student['major'] = 'Math' print(student)
student['age'] = 21 print(student)
|
删除键值对
del 字典名[键]:删除指定键值对。
字典名.pop(键):删除并返回指定键的值。
字典名.clear():清空字典所有键值对。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| student = {'name': 'Alice', 'age': 21, 'major': 'Math'}
del student['major'] print(student)
age = student.pop('age') print(age) print(student)
student.clear() print(student)
|
字典的遍历
字典提供多种方式遍历键、值或键值对:
遍历所有键(keys())
1 2 3 4 5 6 7 8 9
| fruit_prices = {'apple': 5, 'banana': 3, 'orange': 4}
for fruit in fruit_prices: print(fruit)
for fruit in fruit_prices.keys(): print(fruit)
|
遍历所有值(values())
1 2 3 4
| fruit_prices = {'apple': 5, 'banana': 3, 'orange': 4}
for price in fruit_prices.values(): print(price)
|
遍历键值对(items())
1 2 3 4 5 6 7 8 9 10
| fruit_prices = {'apple': 5, 'banana': 3, 'orange': 4}
for fruit, price in fruit_prices.items(): print(f"水果:{fruit},价格:{price}元")
|
字典的常用方法
除上述操作外,字典还有以下常用方法:
| 方法 |
功能描述 |
示例 |
keys() |
返回所有键的视图(类似列表) |
dict.keys() |
values() |
返回所有值的视图 |
dict.values() |
items() |
返回所有键值对的视图(元组形式) |
dict.items() |
get(key, default) |
获取键对应的值,不存在则返回 default |
student.get('gender', 'Unknown') |
pop(key) |
删除并返回键对应的值 |
student.pop('age') |
popitem() |
删除并返回最后插入的键值对(3.7+ 有序) |
dict.popitem() |
update(other) |
用另一个字典的键值对更新当前字典 |
dict.update({'a': 1, 'b': 2}) |
copy() |
复制字典(浅拷贝) |
dict.copy() |
示例:update() 和 copy()
1 2 3 4 5 6 7 8 9 10 11
| dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} dict1.update(dict2) print(dict1)
dict3 = dict1.copy() dict3['a'] = 100 print(dict1) print(dict3)
|
字典的特性与适用场景
特性
- 无序到有序:Python 3.7+ 中,字典保留插入顺序;3.6 及以下无序。
- 可变:可动态添加、修改、删除键值对。
- 高效查找:通过键查找值的时间复杂度为 O (1),远快于列表的 O (n)。
适用场景
- 存储关联数据:如用户信息(姓名、年龄、邮箱)、配置参数(键为参数名,值为参数值)。
- 快速查找:需要通过唯一标识(键)快速定位数据时(如缓存、索引)。
- 数据聚合:将多个相关值组合成一个结构(如统计单词出现次数:
{'apple': 5, 'banana': 3})。