06 字典基础
Python 字典(dict)是一种可变、无序的键值对集合,键必须是不可变类型(如字符串、数字或元组),值可以是任意类型。字典通过键快速查找值,效率极高。
创建字典
使用花括号 {} 或 dict() 构造函数创建字典:
| # 直接创建,冒号前面的是键,后面的是值,这里定义了两个键值对
dict1 = {'name': 'Alice', 'age': 25}
# 使用 dict() 构造函数
dict2 = dict(name='Bob', age=30)
# 空字典
empty_dict = {}
|
访问字典元素
通过键访问值,若键不存在会引发 KeyError:
| person = {'name': 'Alice', 'age': 25}
print(person['name']) # 输出: Alice
print(person['sex']) # 报错并输出: keyError
# 因此可以使用 get() 避免错误
print(person.get('address', '默认值')) # 输出: 默认值
|
字典常见操作
字典赋值:直接对键赋值可修改或添加元素
| person = {'name': 'Alice', 'age': 25}
person['age'] = 26 # 修改值
person['address'] = 'NY' # 添加新键值对,{'name': 'Alice', 'age': 26, 'address': 'NY'}
|
删除元素:使用 del 或 pop() 删除键值对
| person = {'name': 'Alice', 'age': 25, 'address': 'NY'}
del person['age'] # 删除键 'age'
address = person.pop('address') # 删除并返回值,相当于做了两步操作
print(person) # {'name': 'Alice'}
print(address) # NY
|
字典常用方法
keys() / values() / items()
| person = {'name': 'Alice', 'age': 25}
print(person.keys()) # 输出键列表: dict_keys(['name', 'age'])
print(person.values()) # 输出值列表: dict_values(['Alice', 25])
print(person.items()) # 输出键值对: dict_items([('name', 'Alice'), ('age', 25)])
|
update() 合并字典
| dict1 = {'a': 1}
dict2 = {'b': 2}
dict1.update(dict2) # dict1 变为 {'a': 1, 'b': 2}
|
clear() 清空字典
字典拓展用法
-
字典推导式:类似列表推导式,生成字典
| # 下方的x既充当了键也充当了值,键为x,值为x的平方
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
|
-
嵌套字典:字典的值可以是另一个字典
| users = {
'user1': {'age': 22, 'email': 'user1@example.com'},
'user2': {'age': 30, 'email': 'user2@example.com'}
}
print(users['user1']['email']) # 输出: user1@example.com
|
-
字典与 JSON 转换:使用 json 模块实现字典与 JSON 字符串的转换:
| import json
person = {'name': 'Alice', 'age': 25}
# 字典转 JSON
json_str = json.dumps(person) # '{"name": "Alice", "age": 25}'
# JSON 转字典
new_dict = json.loads(json_str) # {'name': 'Alice', 'age': 25}
|
-
有序字典(OrderedDict)
collections.OrderedDict 保留键的插入顺序(Python 3.7+ 后普通字典已有序):
| from collections import OrderedDict
od = OrderedDict([('a', 1), ('b', 2)])
|
-
默认字典(defaultdict)
collections.defaultdict 为不存在的键提供默认值:
| from collections import defaultdict
dd = defaultdict(int) # 默认值为 0
dd['count'] += 1 # 自动初始化 'count' 为 0
print(dd['count']) # 输出为1
|
字典查找时间复杂度为 O(1),适合高频查询场景。同时注意避免在循环中频繁修改字典结构,可能影响哈希表性能。