字典
字典是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')) # 25 print(person.get('country')) # none print(person.get('country', 'usa')) # 指定默认值 'usa' # 检查键是否存在 print('name' in person) # true print('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() 即 0 word_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'] = 1 od['b'] = 2 od['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'] = 3 print(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 # 字典转json person = {'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编程效率和代码质量。
到此这篇关于python 字典 (dictionary) 详解的文章就介绍到这了,更多相关python 字典 dictionary内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论