Python 字典的实用技巧
Python 字典(dict)是一种可变的、无序的数据结构,以键值对的形式存储数据。字典允许我们使用唯一的键来快速访问相应的值,具有查找速度快、灵活性强等优点。在实际开发中,字典被广泛用于存储和管理数据。
1、创建字典
- 使用字面量创建
这是最常见的创建字典的方式,使用花括号 {} 并指定键值对。
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(person)
- 使用 dict() 构造函数
可以通过传入键值对列表或关键字参数来创建字典。
# 通过键值对列表创建
person = dict([('name', 'Bob'), ('age', 30), ('city', 'Los Angeles')])
print(person)
# 通过关键字参数创建
person = dict(name='Charlie', age=35, city='Chicago')
print(person)
2、字典的访问
- 使用键直接访问
如果键存在,可直接通过键获取对应的值;若键不存在,会抛出 KeyError 异常。
person = {'name': 'Alice', 'age': 25}
print(person['name']) # 输出: Alice
# print(person['gender']) # 会抛出 KeyError 异常
- 使用 get() 方法
get() 方法在键存在时返回对应的值,键不存在时返回默认值(默认为 None),避免了 KeyError 异常。
person = {'name': 'Alice', 'age': 25}
print(person.get('name')) # 输出: Alice
print(person.get('gender', 'Unknown')) # 输出: Unknown
3、字典的更新与合并
- 直接修改字典的值
person={'name': 'Alice', 'age': 11, 'city': 'New York'}
# 修改字典中的值
person["age"] = 31
print(person) # 输出: {'name': 'Alice', 'age': 31, 'city': 'New York'}
- 使用 update() 方法
update() 方法可以将一个字典的键值对更新到另一个字典中,如果有相同的键,会覆盖原有的值。
person = {'name': 'Alice', 'age': 25}
new_info = {'age': 26, 'city': 'New York'}
person.update(new_info)
print(person) # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York'}
- 使用字典解包(Python 3.5+)
可以使用字典解包的方式合并多个字典。
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # 输出: {'a': 1, 'b': 3, 'c': 4}
4、添加新键值对
person={'name': 'Alice', 'age': 31, 'city': 'New York'}
# 添加新的键值对
person["email"] = "alice@example.com"
print(person) # 输出: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
5、字典的删除操作
- 使用 popitem() 方法
popitem() 方法会随机删除并返回字典中的一个键值对(在 Python 3.7+ 中,会按照插入顺序删除最后一个键值对)。
person = {'name': 'Alice', 'age': 25}
key, value = person.popitem()
print(key, value)
- 使用 pop() 方法
pop() 方法会删除指定键的键值对,并返回该键对应的值。如果键不存在,可以指定默认值,避免抛出 KeyError 异常。
person = {'name': 'Alice', 'age': 25}
age = person.pop('age')
print(age) # 输出: 25
print(person) # 输出: {'name': 'Alice'}
- 使用 del 关键字
可以通过 del 关键字删除指定键的键值对,如果键不存在会抛出 KeyError 异常。
person = {'name': 'Alice', 'age': 25}
del person['age']
print(person) # 输出: {'name': 'Alice'}
6、字典的遍历
- 遍历键
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key in person:
print(key)
也可以使用 keys() 方法,效果相同:
for key in person.keys():
print(key)
- 遍历值
for value in person.values():
print(value)
- 同时遍历键和值
for key, value in person.items():
print(key, value)
7、检查键是否存在
可以使用 in 关键字检查某个键是否存在于字典中。
person = {'name': 'Alice', 'age': 25}
if 'name' in person:
print('Name exists in the dictionary.')
8、获取所有键、值或键值对
person = {'name': 'Alice', 'age': 25}
# 获取所有键
keys = person.keys()
print(keys) # 输出: dict_keys(['name', 'age'])
# 获取所有值
values = person.values()
print(values) # 输出: dict_values(['Alice', 25])
# 获取所有键值对
items = person.items()
print(items) # 输出: dict_items([('name', 'Alice'), ('age', 25)])
9、字典推导式
可以使用字典推导式快速创建字典。
numbers = [1, 2, 3, 4]
squares = {num: num**2 for num in numbers}
print(squares) # 输出: {1: 1, 2: 4, 3: 9, 4: 16}
10、深拷贝字典
深拷贝能够确保复制的副本与原始数据独立。
import copy
# 创建一个字典
original_dict = {'a': 1, 'b': 2, 'c': {'d': 3}}
# 深拷贝字典
copied_dict = copy.deepcopy(original_dict)
# 修改原始字典
original_dict['c']['d'] = 4
print(copied_dict) # 输出: {'a': 1, 'b': 2, 'c': {'d': 3}}