python的字典扩展操作(collections模块)

本文深入探讨了Python标准库collections中的ChainMap和Counter类。ChainMap允许将多个字典组合成一个,支持所有字典操作;Counter则用于高效计数,如统计字符串中各字符的出现次数或单词频率。文章通过实例演示了这两种数据结构的创建、操作及高级功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.概览

keyvalue
ChainMap类似于字典的类,将多个字典组合成一个字典,并且支持字典的所有操作
Counter用于计数

2.ChainMap

from collections import ChainMap

a = {"a": 1}
b = {"b": 2}
c = {"c": 3}

# 1.生成chainmap类型的字典数据
new_dict = ChainMap(a, b, c)
print(new_dict)

# 2.支持所有的dict字典的增删改查
# 新增的元素存在于第一个字典中
new_dict["e"] = 111
print(new_dict)

# 更新的元素,存在于第一个字典中
new_dict.update({"f": 5})
print(new_dict)

del new_dict["a"]
print(new_dict)

new_dict["a"] = "改变a的value"
print(new_dict)

new_dict.items()
new_dict.keys()
new_dict.values()
new_dict.get("A", 222)

print(new_dict.new_child())
print(new_dict.new_child(m=b))
print(new_dict.maps)

3.Counter

from collections import Counter

# 统计字符串中每个字符出现的次数, 并返回一个key: 数量的字典
new_dict = Counter("helloword")
print(new_dict)

# 统计单词出现的次数
new_dict = "hello word".split()
new_dict = Counter(new_dict)
print(new_dict)

new_dict = Counter({"a": 1, "b": 2})
print(new_dict)

new_dict = Counter(cats=3, dogs=4, haha=5, heheh=6)
print(new_dict)

# 返回一个迭代器, 重复每个元素 * 次数
print(list(new_dict.elements()))

# 返回new_dict中最常见的两个元素, 以及他们出现的次数, 2为参数
print(new_dict.most_common(2))

# 用bb中的元素更新aa中的元素(相减)
aa = Counter(a=3, b=2, c=2, e=5)
bb = Counter(a=1, b=2, c=3, d=4)
aa.subtract(bb)
print(aa)