字典(dict)是Python中非常重要的内置数据类型,它以键值对的形式存储数据。以下是字典的常用操作方法:
# 空字典
empty_dict = {} # {}
empty_dict = dict() # {}
# 直接创建
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 使用dict()构造函数
person = dict(name='Alice', age=25, city='New York')
# {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 从键值对序列创建
person = dict([('name', 'Alice'), ('age', 25), ('city', 'New York')])
#{'name': 'Alice', 'age': 25, 'city': 'New York'}
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 通过键访问
print(person['name']) # 输出: Alice
# 使用get()方法,键不存在时返回None或默认值
print(person.get('age')) # 输出: 25
print(person.get('country')) # 输出: None 没有查找到结果
print(person.get('country', 'USA')) # 输出: USA 查找不到值返回默认值USA
person = {'name': 'Alice', 'age': 25}
# 添加新键值对
person['city'] = 'New York'
# {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 修改现有键的值
person['age'] = 26
# {'name': 'Alice', 'age': 26, 'city': 'New York'}
# 使用update()合并字典
person.update({'country': 'USA', 'age': 27}) # age会被更新,country会被添加
# {'name': 'Alice', 'age': 27, 'city': 'New York', 'country': 'USA'}
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# del语句删除指定键
del person['age']
# {'name': 'Alice', 'city': 'New York'}
# pop()删除并返回指定键的值
city = person.pop('city')
# {'name': 'Alice'}
# popitem()删除并返回最后插入的键值对(3.7+有序)
key, value = person.popitem()
print(key, value) # name Alice
# clear()清空字典
person.clear()
person = {'name': 'Alice', 'age': 25}
# in关键字
if 'name' in person:
print("Name exists") # Name exists
# not in关键字
if 'city' not in person:
print("City does not exist") # City does not exist
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 遍历所有键
for key in person:
print(key) #name age city
# 等价于
for key in person.keys():
print(key) #name age city
# 遍历所有值
for value in person.values():
print(value) # Alice 25 New York
# 遍历所有键值对
for key, value in person.items():
print(f"{key}: {value}")
# name: Alice
# age: 25
# city: New York
# 创建平方字典
squares = {x: x*x for x in range(6)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 条件筛选
even_squares = {x: x*x for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 获取字典长度(键的数量)
length = len(person) # 3
# 复制字典
person_copy = person.copy()
person_copy = dict(person)
# 设置默认值(如果键不存在则设置默认值)
person.setdefault('country', 'USA')
# {'name': 'Alice', 'age': 25, 'city': 'New York','country':'USA'}
# 获取所有键、值、键值对
keys = person.keys()
# dict_keys(['name', 'age', 'city', 'country'])
values = person.values()
# dict_values(['Alice', 25, 'New York', 'USA'])
items = person.items()
# dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York'), ('country', 'USA')])
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# 方法1: 使用update()
merged = dict1.copy()
merged.update(dict2)
# 方法2: 使用**解包(Python 3.5+)
merged = {**dict1, **dict2}
# 方法3: Python 3.9+ 使用 | 运算符
merged = dict1 | dict2
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 按键排序
sorted_by_key = {k: person[k] for k in sorted(person)}
# {'age': 25, 'city': 'New York', 'name': 'Alice'}
# 按值排序
sorted_by_value = {k: v for k, v in sorted(person.items(), key=lambda item: str(item[1]))}
# {'age': 25, 'name': 'Alice', 'city': 'New York'}
# 注意值的类型要保持一致
字典是Python中非常高效和灵活的数据结构,掌握这些操作方法可以大大提高编程效率。