Python 字典(Dictionary):高效数据映射的强大工具
在 Python 中,字典是一种基于键值对(key-value pairs)的数据结构,能够高效地进行数据映射(data mapping)和快速查找(efficient lookup)。字典以无序(unordered)形式存储数据,每个键必须是不可变且可哈希的(immutable and hashable),而值可以是任意对象。下面将详细讲解字典的创建、访问、常用操作以及高级用法(Common Operations and Advanced Applications)。
1. 字典的基本概念
示例代码:
# 定义一个表示学生基本信息的字典
student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
提示: "name"、"age"、"major" 都是键,分别映射到相应的值
选择合适的键(key)能提高代码的可读性和维护性。(enhance code readability and maintainability)
2. 字典的创建与初始化
字典可以通过多种方式创建(a multitude of methods),下面列举几种常见方法:
- 使用大括号 {}
scores = {"Math": 95, "Physics": 90, "Chemistry": 88}
- 使用 dict() 构造函数
info = dict(name="Bob", city="New York", age=25)
- 字典推导式(dictionary comprehension)
# 创建键为数字,值为数字平方的字典
squares = {x: x**2 for x in range(1, 6)} # 结果:{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
小技巧: 字典推导式不仅语法简洁,还能用于过滤和转换数据(Filter and Transform Data)。
3. 访问与操作字典
3.1 访问字典元素
- 使用索引操作符
print(scores["Math"]) # 输出:95
- 注意:若键不存在会抛出 KeyError
- (A KeyError will be raised if the key does not exist)
- 使用 get() 方法
print(scores.get("Biology", "Not Found")) # 键不存在时返回默认值
3.2 修改和添加元素
- 修改已有键的值: scores["Math"] = 98
- 添加新键值对: scores["Biology"] = 92
3.3 删除字典中的元素
- 使用 pop() 删除指定键并返回其值:
math_score = scores.pop("Math")
- 使用 popitem() 删除最后插入的键值对(Python 3.7+):
last_item = scores.popitem()
注意: 修改和删除操作会改变字典的结构,请谨慎操作。
4. 遍历字典
遍历字典时,可以使用 for 循环轻松访问每个键、值或键值对:
- 遍历键:
for key in student: print(key, "->", student[key])
- 遍历键值对:
for key, value in student.items(): print(f"{key} -> {value}")
建议: 在处理大量数据时,遍历字典能够帮助你逐步处理每个数据项
(Iterating through a dictionary enables you to process each data item step by step)
5. 字典的高级用法
5.1 合并字典
- 使用 update() 方法
extra_scores = {"English": 85, "History": 90} scores.update(extra_scores)
- Python 3.9+ 合并运算符 |
dict1 = {"a": 1, "b": 2} dict2 = {"b": 3, "c": 4} merged = dict1 | dict2 # 结果:{"a": 1, "b": 3, "c": 4}
5.2 字典推导式的灵活应用
- 过滤字典中的数据
# 仅保留分数大于80的科目
high_scores = {subject: score for subject, score in scores.items() if score > 80}
5.3 嵌套字典(Nested Dictionary)
- 存储更复杂的数据结构
students = { "Alice": {"age": 21, "major": "Computer Science"}, "Bob": {"age": 22, "major": "Mathematics"} }
print(students["Alice"]["major"])
# 输出:Computer Science 嵌套字典适用于描述具有层次关系的数据,如数据库记录或配置文件。
通过以上详细讲解, 对Python 字典的创建、访问、遍历和高级用法应该有了深入了解。