python - 字典

79 阅读3分钟

在 Python 中,字典(Dictionary)  是一种可变的、无序的(Python 3.7+ 后按插入顺序排序)键值对(key-value)集合,用于高效存储和检索数据。以下是 Python 字典的详细用法和示例:


1. 创建字典

方式 1:使用花括号 {}

# 空字典
empty_dict = {}
 
# 带初始值的字典
person = {"name": "Alice", "age": 25, "city": "New York"}

方式 2:使用 dict() 构造函数

person = dict(name="Bob", age=30, city="London")  # 关键字参数
person = dict([("name", "Charlie"), ("age", 35)])  # 可迭代对象(元组列表)

2. 访问字典值

通过键访问

print(person["name"])  # 输出: Alice

⚠️ 如果键不存在,会抛出 KeyError

使用 get() 方法(推荐)

print(person.get("age"))       # 输出: 25
print(person.get("country", "USA"))  # 如果键不存在,返回默认值 "USA"

3. 修改字典

添加或更新键值对

person["email"] = "alice@example.com"  # 添加新键值对
person["age"] = 26                     # 更新已有键的值

使用 update() 批量添加/更新

person.update({"job": "Engineer", "city": "Berlin"})  # 合并另一个字典

4. 删除键值对

使用 del 语句

del person["city"]  # 删除键 "city"

⚠️ 如果键不存在,会抛出 KeyError

使用 pop() 方法

age = person.pop("age")  # 删除键 "age" 并返回其值

使用 popitem()(Python 3.7+ 删除最后一个键值对)

key, value = person.popitem()  # 删除并返回最后一个键值对

清空字典

person.clear()  # 清空字典

5. 遍历字典

遍历所有键

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}")

6. 字典常用方法

方法描述
dict.keys()返回所有键的视图
dict.values()返回所有值的视图
dict.items()返回所有键值对的视图
dict.get(key, default)安全获取键的值
dict.update(other_dict)合并另一个字典
dict.pop(key)删除并返回指定键的值
dict.popitem()删除并返回最后一个键值对
dict.clear()清空字典

7. 字典推导式(Dictionary Comprehension)

# 示例:平方数字典
squares = {x: x**2 for x in range(5)}
print(squares)  # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
 
# 示例:过滤字典
original_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
filtered_dict = {k: v for k, v in original_dict.items() if v % 2 == 0}
print(filtered_dict)  # 输出: {'b': 2, 'd': 4}

8. 字典的高级用法

默认字典 collections.defaultdict

from collections import defaultdict
 
# 如果键不存在,自动初始化为 0
dd = defaultdict(int)
dd["count"] += 1  # 自动创建键 "count" 并赋值为 1

有序字典 collections.OrderedDict

from collections import OrderedDict
 
od = OrderedDict()
od["a"] = 1
od["b"] = 2
print(od)  # 输出: OrderedDict([('a', 1), ('b', 2)])

字典合并(Python 3.9+)

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = dict1 | dict2  # 合并字典(dict2 的值覆盖 dict1)
print(merged_dict)  # 输出: {'a': 1, 'b': 3, 'c': 4}

9. 字典的常见应用

  1. 统计词频

    text = "hello world hello python"
    words = text.split()
    freq = {word: words.count(word) for word in set(words)}
    print(freq)  # 输出: {'hello': 2, 'world': 1, 'python': 1}
    
  2. JSON 数据处理

    import json
    data = {"name": "Alice", "age": 25}
    json_str = json.dumps(data)  # 字典转 JSON 字符串
    parsed_data = json.loads(json_str)  # JSON 字符串转字典
    
  3. 缓存(Memoization)

    cache = {}
    def fibonacci(n):
        if n in cache:
            return cache[n]
        if n <= 1:
            return n
        cache[n] = fibonacci(n-1) + fibonacci(n-2)
        return cache[n]
    

10. 注意事项

  • 键必须是不可变类型(如 strinttuple),不能用 list 或 dict 作为键。
  • 字典是无序的(Python 3.7+ 后按插入顺序排序,但不应依赖此特性)。
  • 高效查找:字典的查找、插入、删除操作平均时间复杂度为 O(1)

总结

Python 字典是一种强大的数据结构,适用于快速查找、计数、缓存和结构化数据存储。掌握字典的基本操作和高级用法(如推导式、defaultdict)可以大幅提升代码效率。