字典是Python中一种可变的无序键值对集合,也称为关联数组或哈希表。
基本特性
- 键值对结构:存储数据为
key: value形式 - 无序性:Python 3.7+中字典保持插入顺序,但不应依赖顺序操作
- 可变性:可以动态添加、修改或删除键值对
- 键的唯一性:每个键必须是唯一的
- 键的类型限制:键必须是不可变类型(字符串、数字、元组等)
创建字典
# 空字典
empty_dict = {}
empty_dict = dict()
# 直接创建
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 使用dict()构造函数
person = dict(name='Alice', age=25, city='New York') # 键不用引号
# 从键值对序列创建
pairs = [('name', 'Bob'), ('age', 30)]
person = dict(pairs)
# 字典推导式
squares = {x: x*x for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}访问字典元素
person = {'name': 'Alice', 'age': 25}
# 通过键访问
print(person['name']) # 输出: Alice
# get()方法 - 安全访问,键不存在返回None或默认值
print(person.get('age')) # 25
print(person.get('salary')) # None
print(person.get('salary', 0)) # 0 (设置默认值)
# 检查键是否存在
print('name' in person) # True
print('salary' not in person) # True修改字典
person = {'name': 'Alice', 'age': 25}
# 添加/更新元素
person['city'] = 'New York' # 添加
person['age'] = 26 # 更新
# update()方法 - 批量更新
person.update({'age': 27, 'job': 'Engineer'})
# setdefault() - 键不存在时设置默认值
person.setdefault('country', 'USA') # 如果country不存在,设置为USA删除元素
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# del语句
del person['age'] # 删除键'age'
# pop() - 删除并返回值
city = person.pop('city') # 删除'city'并返回'New York'
# popitem() - 删除并返回最后插入的键值对(Python 3.7+)
key, value = person.popitem()
# clear() - 清空字典
person.clear()字典方法
方法 | 描述 |
| 返回所有键的视图 |
| 返回所有值的视图 |
| 返回所有键值对的视图 |
| 安全获取值 |
| 设置默认值 |
| 批量更新 |
| 删除并返回值 |
| 删除并返回最后插入的项 |
| 清空字典 |
| 浅拷贝 |
字典视图对象
person = {'name': 'Alice', 'age': 25}
# keys() - 键视图
print(person.keys()) # dict_keys(['name', 'age'])
# values() - 值视图
print(person.values()) # dict_values(['Alice', 25])
# items() - 键值对视图
print(person.items()) # dict_items([('name', 'Alice'), ('age', 25)])
# 视图是动态的,会反映字典的变化
person['city'] = 'NY'
print(person.keys()) # 现在包含'city'字典遍历
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 遍历键
for key in person:
print(key)
for key in person.keys():
print(key)
# 遍历值
for value in person.values():
print(value)
# 遍历键值对
for key, value in person.items():
print(f"{key}: {value}")字典与列表的比较
特性 | 字典(Dictionary) | 列表(List) |
存储方式 | 键值对 | 有序序列 |
访问方式 | 通过键 | 通过索引 |
顺序 | Python 3.7+保持插入顺序 | 保持插入顺序 |
可变性 | 可变 | 可变 |
查找速度 | O(1) - 非常快 | O(n) - 线性搜索 |
内存占用 | 更高 | 更低 |
使用场景
- 快速查找:当需要根据键快速查找值时
- 存储关联数据:如数据库记录、配置设置等
- 计数:使用字典统计元素出现次数
- 缓存数据:存储计算结果以避免重复计算
# 统计单词频率
text = "hello world hello python world python python"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # {'hello': 2, 'world': 2, 'python': 3}
# 字典作为缓存
cache = {}
def expensive_computation(x):
if x not in cache:
# 模拟耗时计算
result = x * x
cache[x] = result
return cache[x]字典是Python中极其重要的数据结构,几乎在所有Python程序中都有广泛应用。
















