Python案例中的默认字典怎么用?

wen python案例 4

本文目录导读:

Python案例中的默认字典怎么用?

  1. 基本用法
  2. 常用的默认值类型
  3. 使用自定义函数作为默认值工厂
  4. 实际应用案例
  5. 与普通字典的对比
  6. 注意事项

在Python中,默认字典(defaultdict)是collections模块提供的一个非常有用的数据结构,它和普通字典的区别在于:当访问一个不存在的键时,不会抛出KeyError,而是会自动创建一个默认值

基本用法

from collections import defaultdict
# 创建一个默认字典,当键不存在时自动生成一个空列表
dd = defaultdict(list)
# 现在可以直接向不存在的键添加元素
dd['fruits'].append('apple')
dd['fruits'].append('banana')
dd['vegetables'].append('carrot')
print(dd)  # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana'], 'vegetables': ['carrot']})
print(dd['fruits'])  # ['apple', 'banana']
print(dd['meat'])    # []  # 不存在的键返回空列表,不会报错

常用的默认值类型

from collections import defaultdict
# 1. 默认值:空列表
list_default = defaultdict(list)
list_default['a'].append(1)  # 自动创建空列表
# 2. 默认值:空集合
set_default = defaultdict(set)
set_default['a'].add(1)      # 自动创建空集合
# 3. 默认值:整数0
int_default = defaultdict(int)
int_default['apple'] += 1    # 自动创建0,然后加1
int_default['apple'] += 2    # 现在值是3
print(int_default['apple'])  # 3
print(int_default['banana']) # 0  # 不存在的键返回0
# 4. 默认值:字符串
str_default = defaultdict(str)
print(str_default['key'])    # ''  # 空字符串
# 5. 默认值:None
none_default = defaultdict(None)
# print(none_default['key'])  # KeyError,因为None不是可调用对象

使用自定义函数作为默认值工厂

from collections import defaultdict
# 自定义函数
def default_value():
    return {'count': 0, 'items': []}
dd = defaultdict(default_value)
# 访问不存在的键,会自动执行default_value函数
data = dd['user1']
print(data)  # {'count': 0, 'items': []}
# 修改数据
dd['user1']['count'] = 5
dd['user1']['items'].extend(['商品1', '商品2'])
print(dd['user1'])  # {'count': 5, 'items': ['商品1', '商品2']}
print(dd['user2'])  # {'count': 0, 'items': []}  # 新的默认值

实际应用案例

案例1:分组统计

from collections import defaultdict
# 按首字母分组单词
words = ['apple', 'banana', 'avocado', 'blueberry', 'cherry', 'coconut']
word_groups = defaultdict(list)
for word in words:
    first_letter = word[0]
    word_groups[first_letter].append(word)
print(dict(word_groups))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry', 'coconut']}

案例2:统计词频

from collections import defaultdict
# 统计文章中每个单词出现的次数
text = "the cat and the dog and the bird"
word_count = defaultdict(int)
for word in text.split():
    word_count[word] += 1
print(dict(word_count))
# {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}

案例3:树形数据结构

from collections import defaultdict
# 创建无限层级的树
def tree():
    return defaultdict(tree)
# 创建一棵树
categories = tree()
categories['电子产品']['手机']['苹果'] = []
categories['电子产品']['手机']['华为'] = []
categories['电子产品']['电脑']['联想'] = []
categories['食品']['水果']['苹果'] = []
print(categories['电子产品']['手机']['苹果'])  # []
print(categories['电子产品']['手机']['三星'])  # []  # 自动创建

与普通字典的对比

from collections import defaultdict
# 普通字典的写法
regular_dict = {}
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
for fruit in fruits:
    if fruit not in regular_dict:  # 需要检查键是否存在
        regular_dict[fruit] = 0
    regular_dict[fruit] += 1
print(regular_dict)  # {'apple': 3, 'banana': 2, 'orange': 1}
# 默认字典的简洁写法
fruit_count = defaultdict(int)
for fruit in fruits:
    fruit_count[fruit] += 1  # 不需要检查键是否存在
print(dict(fruit_count))  # {'apple': 3, 'banana': 2, 'orange': 1}

注意事项

  1. 默认值工厂函数必须是一个可调用对象(函数、类等)或无参数
  2. defaultdict在序列化(如json.dumps)时需要先转换为普通字典
  3. 对于复杂的默认值,使用lambda或自定义函数
from collections import defaultdict
# 错误的写法
# dd = defaultdict([])  # TypeError: first argument must be callable or None
# 正确的写法
dd = defaultdict(list)  # list是一个可调用对象
dd = defaultdict(lambda: [])  # 也可以使用lambda

默认字典在处理需要为不存在的键自动创建默认值的情况时非常方便,能大大简化代码逻辑。

抱歉,评论功能暂时关闭!