1. Python字典:键值映射的艺术与实战
字典是Python中最灵活且实用的数据结构之一,它以一种直观的键值对形式存储数据,就像现实生活中的字典一样,通过"单词"快速找到对应的"解释"。在数据处理、Web开发和系统配置等场景中,字典都扮演着核心角色。
1.1 字典基础:从创建到访问
创建字典最直接的方式是使用花括号语法:
python复制user_profile = {
"name": "张伟",
"age": 28,
"occupation": "数据分析师",
"skills": ["Python", "SQL", "机器学习"]
}
访问字典值时,有两种主要方式:
- 直接通过键访问:
user_profile["name"] - 使用get()方法安全访问:
user_profile.get("address", "未填写")
重要提示:直接访问不存在的键会引发KeyError,而get()方法在键不存在时会返回None或指定的默认值
字典的键必须是不可变类型(字符串、数字、元组等),而值可以是任意Python对象。这种灵活性使得字典可以构建非常复杂的数据结构:
python复制company_data = {
"departments": {
"研发部": {
"headcount": 15,
"projects": ["A项目", "B项目"]
},
"市场部": {
"headcount": 8,
"budget": 500000
}
},
"founded_year": 2015
}
1.2 字典的CRUD操作
字典的基本操作遵循CRUD原则(创建、读取、更新、删除):
python复制# 创建
empty_dict = {}
dict_from_keys = dict.fromkeys(['a', 'b', 'c'], 0)
# 读取
name = user_profile['name']
age = user_profile.get('age')
# 更新
user_profile['age'] = 29 # 修改已有键
user_profile['email'] = 'zhangwei@example.com' # 添加新键
# 删除
del user_profile['email'] # 删除键值对
removed_value = user_profile.pop('age') # 删除并返回值
批量更新可以使用update()方法:
python复制update_data = {
'hobby': '摄影',
'city': '北京'
}
user_profile.update(update_data)
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 字典的高级操作技巧
2.1 字典推导式:简洁创建字典
类似于列表推导式,字典推导式提供了一种简洁的创建字典的方式:
python复制# 创建数字平方字典
squares = {x: x*x for x in range(1, 6)}
# 输出: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 筛选字典项
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered = {k: v for k, v in original.items() if v > 2}
# 输出: {'c': 3, 'd': 4}
2.2 遍历字典的多种方式
Python提供了多种遍历字典的方式,适用于不同场景:
python复制# 遍历键
for key in user_profile.keys():
print(key)
# 遍历值
for value in user_profile.values():
print(value)
# 遍历键值对(最常用)
for key, value in user_profile.items():
print(f"{key}: {value}")
# 同时获取索引和键值对(Python 3.7+保持插入顺序)
for idx, (key, value) in enumerate(user_profile.items()):
print(f"{idx}. {key} => {value}")
2.3 字典的默认值处理
处理可能不存在的键时,有几种优雅的方式:
python复制# 方法1:使用get()设置默认值
value = user_profile.get('address', '未知')
# 方法2:使用setdefault()(不存在时设置并返回默认值)
skills = user_profile.setdefault('skills', [])
# 方法3:使用collections.defaultdict
from collections import defaultdict
dd = defaultdict(list) # 不存在的键自动初始化为空列表
dd['skills'].append('Python')
3. 字典的实用函数库
3.1 安全访问嵌套字典
处理多层嵌套字典时,安全访问深层键值是一个常见需求:
python复制def safe_get(d, keys, default=None):
"""
安全获取嵌套字典中的值
:param d: 目标字典
:param keys: 键的列表或元组,表示访问路径
:param default: 键不存在时的默认返回值
:return: 找到的值或默认值
"""
current = d
for key in keys:
if isinstance(current, dict) and key in current:
current = current[key]
else:
return default
return current
# 使用示例
config = {
'database': {
'host': 'localhost',
'credentials': {
'username': 'admin',
'password': 'secret'
}
}
}
username = safe_get(config, ['database', 'credentials', 'username'])
# 返回: 'admin'
port = safe_get(config, ['database', 'port'], 3306)
# 返回: 3306(默认值)
3.2 字典的合并策略
合并两个字典时,根据业务需求有不同的策略:
python复制def merge_dicts(dict1, dict2, strategy='overwrite'):
"""
合并两个字典,支持不同策略
:param dict1: 基础字典
:param dict2: 要合并的字典
:param strategy: 合并策略 ('overwrite', 'keep', 'deep')
:return: 合并后的新字典
"""
if strategy == 'overwrite':
return {**dict1, **dict2}
elif strategy == 'keep':
return {**dict2, **dict1} # dict1优先
elif strategy == 'deep':
result = dict1.copy()
for key, value in dict2.items():
if (key in result and isinstance(result[key], dict)
and isinstance
