Python 字典 (Dictionary) 详解_python dictionary
文章目录
- 字典
-
- 1.基本特性
- 2.创建字典
- 3.访问元素
- 4.修改字典
- 5.删除元素
- 6.字典遍历
- 7.字典的高级特性
-
- 默认字典 (collections.defaultdict)
- 有序字典
- 计数器
- 8.字典的视图对象
- 9.字典与JSON
- 10.性能考虑
- 11.适用场景
- 小结
字典
字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力。
1.基本特性
- 键值对集合:存储数据形式为 key: value 对
- 无序性:Python 3.7+ 开始保持插入顺序(实现细节,应视为无序)
- 可变性:可以动态添加、修改、删除键值对
- 键的唯一性:每个键必须是唯一的
- 键的可哈希性:键必须是不可变类型(如字符串、数字、元组等)
- 高效查找:基于哈希表实现,查找时间复杂度接近 O(1)
2.创建字典
# 使用花括号(最常用)d1 = {\'name\': \'Alice\', \'age\': 25}# 使用 dict() 构造函数d2 = dict(name=\'Bob\', age=30) # 键作为关键字参数d3 = dict([(\'name\', \'Charlie\'), (\'age\', 35)]) # 从键值对序列# 字典推导式d4 = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}# fromkeys 方法 - 为多个键设置相同的默认值keys = [\'a\', \'b\', \'c\']d5 = dict.fromkeys(keys, 0) # {\'a\': 0, \'b\': 0, \'c\': 0}# 空字典empty_dict = {}empty_dict2 = dict()
3.访问元素
person = {\'name\': \'Alice\', \'age\': 25, \'city\': \'New York\'}# 通过键访问print(person[\'name\']) # \'Alice\'# 使用 get() 方法(避免KeyError)print(person.get(\'age\')) # 25print(person.get(\'country\')) # Noneprint(person.get(\'country\', \'USA\')) # 指定默认值 \'USA\'# 检查键是否存在print(\'name\' in person) # Trueprint(\'country\' in person) # False# 获取所有键、值、键值对print(person.keys()) # dict_keys([\'name\', \'age\', \'city\'])print(person.values()) # dict_values([\'Alice\', 25, \'New York\'])print(person.items()) # dict_items([(\'name\', \'Alice\'), (\'age\', 25), (\'city\', \'New York\')])
4.修改字典
person = {\'name\': \'Alice\', \'age\': 25}# 添加/修改元素person[\'city\'] = \'New York\' # 添加person[\'age\'] = 26 # 修改# update() 方法 - 批量更新person.update({\'age\': 27, \'country\': \'USA\'})# setdefault() - 如果键不存在则设置默认值person.setdefault(\'gender\', \'female\') # 返回 \'female\'person.setdefault(\'name\', \'Bob\') # 不修改,返回 \'Alice\'# 合并字典 (Python 3.9+)dict1 = {\'a\': 1, \'b\': 2}dict2 = {\'b\': 3, \'c\': 4}merged = dict1 | dict2 # {\'a\': 1, \'b\': 3, \'c\': 4}
5.删除元素
person = {\'name\': \'Alice\', \'age\': 25, \'city\': \'New York\'}# del 语句del person[\'age\']# pop() - 删除并返回指定键的值city = person.pop(\'city\') # 返回 \'New York\'# popitem() - 删除并返回最后插入的键值对 (Python 3.7+)key, value = person.popitem() # 可能是任意项(Python 3.7前)# clear() - 清空字典person.clear() # {}# 注意:删除不存在的键会引发 KeyError
6.字典遍历
scores = {\'Alice\': 85, \'Bob\': 92, \'Charlie\': 78}# 遍历键for name in scores: print(name)for name in scores.keys(): print(name)# 遍历值for score in scores.values(): print(score)# 遍历键值对for name, score in scores.items(): print(f\"{name}: {score}\")# 带索引的遍历 (Python 3.7+ 保持插入顺序)for i, (name, score) in enumerate(scores.items()): print(f\"{i+1}. {name}: {score}\")
7.字典的高级特性
默认字典 (collections.defaultdict)
from collections import defaultdict# 为不存在的键提供默认值word_counts = defaultdict(int) # 默认值为 int() 即 0word_counts[\'apple\'] += 1 # 自动初始化为0然后加1# 复杂默认值grouped_data = defaultdict(list)grouped_data[\'fruits\'].append(\'apple\')
有序字典
from collections import OrderedDict# 保持元素插入顺序(Python 3.7+ 普通字典也保持顺序)od = OrderedDict()od[\'a\'] = 1od[\'b\'] = 2od[\'c\'] = 3
计数器
from collections import Counter# 统计元素出现次数words = [\'apple\', \'banana\', \'apple\', \'orange\', \'banana\', \'apple\']word_counts = Counter(words)print(word_counts.most_common(2)) # [(\'apple\', 3), (\'banana\', 2)]
8.字典的视图对象
字典的keys(),values(),items()返回的是视图对象:
d = {\'a\': 1, \'b\': 2}keys = d.keys()# 视图是动态的d[\'c\'] = 3print(keys) # dict_keys([\'a\', \'b\', \'c\'])# 支持集合操作d1 = {\'a\': 1, \'b\': 2}d2 = {\'b\': 3, \'c\': 4}print(d1.keys() & d2.keys()) # {\'b\'}print(d1.keys() - d2.keys()) # {\'a\'}
9.字典与JSON
import json# 字典转JSONperson = {\'name\': \'Alice\', \'age\': 25}json_str = json.dumps(person) # \'{\"name\": \"Alice\", \"age\": 25}\'# JSON转字典person_dict = json.loads(json_str)
10.性能考虑
- 查找速度快:接近 O(1) 时间复杂度
- 内存占用较大:比列表等结构占用更多内存
- 键的选择:
- 使用简单、不可变对象作为键
- 避免使用复杂对象作为键
- 字符串是最常用的键类型
11.适用场景
- 存储对象属性或配置信息
- 快速查找表
- 实现稀疏数据结构
- 缓存计算结果(Memoization)
- 数据分组和聚合
- JSON数据交互
小结
- 字典键必须是可哈希的(不可变类型)
- 允许:字符串、数字、元组(仅包含可哈希元素)
- 不允许:列表、字典、集合等可变类型
- 比较操作:
- == 比较键值对内容
- != 判断是否不相等
- 没有 等比较操作
- 字典在Python 3.6及之前是无序的,3.7+开始保持插入顺序(作为实现细节,3.7正式成为语言特性)
字典是Python中最灵活和强大的数据结构之一,熟练掌握字典的使用可以极大提高Python编程效率和代码质量。