PPZ

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1. 创建字典

使用大括号 {} 创建空字典
empty_dict = {}
print(empty_dict)  # 输出: {}
使用 dict 函数创建字典
# 通过键值对创建字典
person = dict(name="Alice", age=30, city="New York")
print(person)  # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York'}

# 通过其他可迭代对象创建字典
key_value_pairs = [('name', 'Bob'), ('age', 25)]
person = dict(key_value_pairs)
print(person)  # 输出: {'name': 'Bob', 'age': 25}

2. 增加、更新和删除元素

增加或更新元素
# 使用索引赋值语句
person = {'name': 'Alice', 'age': 30}
person['city'] = 'New York'
print(person)  # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York'}

# 更新已有键的值
person['age'] = 31
print(person)  # 输出: {'name': 'Alice', 'age': 31, 'city': 'New York'}
删除元素
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# 使用 del 语句删除指定键的键值对
del person['age']
print(person)  # 输出: {'name': 'Alice', 'city': 'New York'}

# 使用 pop 方法删除指定键的键值对,并返回其值
city = person.pop('city')
print(city)    # 输出: New York
print(person)  # 输出: {'name': 'Alice'}

3. 访问字典元素

person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# 使用键访问对应的值
print(person['name'])  # 输出: Alice

# 使用 get 方法获取键对应的值,如果键不存在,则返回指定的默认值
print(person.get('age', 25))  # 输出: 30
print(person.get('gender', 'unknown'))  # 输出: unknown

# 使用 items 方法遍历字典的键值对
for key, value in person.items():
    print(key, value)
# 输出:
# name Alice
# age 30
# city New York

4. 字典的其他常用方法

person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# 使用 keys 方法获取所有键
keys = person.keys()
print(keys)  # 输出: dict_keys(['name', 'age', 'city'])

# 使用 values 方法获取所有值
values = person.values()
print(values)  # 输出: dict_values(['Alice', 30, 'New York'])

# 使用 len 函数获取字典中键值对的数量
print(len(person))  # 输出: 3

# 使用 in 关键字判断键是否存在于字典中
print('name' in person)  # 输出: True
print('gender' in person)  # 输出: False

5. 字典的高级技巧

使用字典推导式创建字典
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']

# 使用 zip 函数将两个列表组合成字典
person = {key: value for key, value in zip(keys, values)}
print(person)  # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York'}
合并字典
dict1 = {'name': 'Alice', 'age': 30}
dict2 = {'city': 'New York', 'country': 'USA'}

# 使用 update 方法合并字典
dict1.update(dict2)
print(dict1)  # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}

总结

字典是 Python 中非常重要的数据结构,它提供了灵活的键值对存储和访问方式。掌握字典的各种操作方法和高级技巧,对于进行数据处理和编程任务至关重要。

posted on 2024-06-04 09:46  犬卧  阅读(191)  评论(0编辑  收藏  举报