Python 3 字典代码实例
·
字典基础
Python 中的字典是一种可变的、无序的(Python 3.7+ 起保持插入顺序)键值对集合。字典的声明和初始化可以通过以下方式实现:
# 使用花括号创建
dict1 = {'name': 'Alice', 'age': 25}
# 使用 dict() 构造函数
dict2 = dict(name='Bob', age=30)
# 创建空字典
dict3 = {}
# 从键值对序列创建
dict4 = dict([('city', 'Beijing'), ('country', 'China')])
字典访问与修改
使用键可以方便地访问和修改字典中的值:
person = {'name': 'Charlie', 'age': 28, 'city': 'Shanghai'}
# 访问值
print(person['name']) # Charlie
print(person.get('age')) # 28
print(person.get('salary', 0)) # 0(键不存在时返回默认值)
# 修改值
person['age'] = 29
# 添加新键值对
person['job'] = 'Engineer'
# 删除键值对
del person['city']
removed = person.pop('job') # 返回并删除
print(f"Removed: {removed}")
常用字典方法
Python 内置了丰富的字典操作方法:
student = {'name': 'David', 'math': 90, 'english': 85}
# 获取所有键
print(student.keys()) # dict_keys(['name', 'math', 'english'])
# 获取所有值
print(student.values()) # dict_values(['David', 90, 85])
# 获取所有键值对
print(student.items()) # dict_items([...])
# 更新字典
student.update({'physics': 88, 'math': 92})
print(student)
# 清空字典
student.clear()
print(student) # {}
字典遍历
字典支持多种遍历方式,灵活高效:
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# 遍历键(默认)
for name in scores:
print(name)
# 遍历键值对
for name, score in scores.items():
print(f"{name}: {score}")
# 按值排序遍历
for name in sorted(scores, key=scores.get, reverse=True):
print(f"{name}: {scores[name]}")
字典推导式
使用推导式可以简洁地创建和转换字典:
# 从列表创建字典
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 过滤字典
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
evens = {k: v for k, v in original.items() if v % 2 == 0}
print(evens) # {'b': 2, 'd': 4}
# 转换键值
swapped = {v: k for k, v in original.items()}
print(swapped) # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
嵌套字典
处理复杂数据时可以使用嵌套字典结构:
# 嵌套字典表示学生信息
students = {
'Alice': {'age': 20, 'grades': {'math': 90, 'english': 85}},
'Bob': {'age': 22, 'grades': {'math': 78, 'english': 92}}
}
# 访问嵌套值
print(students['Alice']['grades']['math']) # 90
# 遍历嵌套字典
for name, info in students.items():
print(f"\n{name} (age {info['age']}):")
for subject, grade in info['grades'].items():
print(f" {subject}: {grade}")
使用 collections 模块
collections 模块提供了增强的字典类型:
from collections import defaultdict, Counter, OrderedDict
# defaultdict: 自动为缺失键提供默认值
word_count = defaultdict(int)
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
for word in words:
word_count[word] += 1
print(dict(word_count)) # {'apple': 3, 'banana': 2, 'orange': 1}
# Counter: 快速计数
counter = Counter(words)
print(counter.most_common(2)) # [('apple', 3), ('banana', 2)]
# OrderedDict: 有序字典(Python 3.7+ 内置 dict 已支持顺序)
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
字典合并操作
Python 3.9+ 引入了简洁的字典合并语法:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# 使用 | 合并(Python 3.9+)
merged = dict1 | dict2
print(merged) # {'a': 1, 'b': 3, 'c': 4}
# 使用 |= 就地更新
dict1 |= dict2
print(dict1) # {'a': 1, 'b': 3, 'c': 4}
# 传统方式:使用 ** 解包
combined = {**dict1, **dict2}
自定义字典类
继承 dict 可以实现自定义的字典行为:
class CaseInsensitiveDict(dict):
"""不区分大小写的字典"""
def __setitem__(self, key, value):
super().__setitem__(key.lower(), value)
def __getitem__(self, key):
return super().__getitem__(key.lower())
def __contains__(self, key):
return super().__contains__(key.lower())
# 使用自定义字典
cid = CaseInsensitiveDict()
cid['Name'] = 'Alice'
print(cid['name']) # Alice
print('NAME' in cid) # True
性能注意事项
字典操作在 Python 中需要特别注意性能和内存问题:
-
字典的键必须是可哈希(hashable)的对象,如字符串、数字、元组
-
字典查找操作的时间复杂度为 O(1),适合频繁查询场景
-
对于大量数据,考虑使用
collections.Counter进行计数统计 -
避免在循环中频繁创建临时字典,可预先分配或使用
setdefault
以上代码示例涵盖了 Python 3 字典的主要概念和操作,从基础用法到高级技巧,为开发者提供了全面的参考。
更多推荐

所有评论(0)