Python 中的 defaultdict 数据类型

 

首先,defaultdict 是 dict 的一个子类。通常 Python 中字典(dict)是通过键值对来存取的,当索引一个不存在的键时,就会引发 keyerror 异常。那么,defaultdict 就可以解决这个问题,它可以实现为不存的键值返回一个默认值

defaultdict是 collections 包下的一个模块,defaultdict 在初始化时可以提供一个 default_factory 的参数,default_factory 接收一个工厂函数作为参数, 可以是 int、str、list 等内置函数,也可以是自定义函数。

 

001、

>>> str1 = "aaabcdddddeffggg"                  ## 测试字符串
>>> dict1 = {}                            ## 标准字典
>>> for i in str1:
...     dict1[i] += 1                   ## 标准字典无法直接统计字母的个数
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'a'
>>> from collections import defaultdict   ## 从collections模块中导入defaultdict函数
>>> dict2 = defaultdict(int)  ## 为不存在的键值返回一个默认值
>>> for j in str1:
...     dict2[j] += 1
...
>>> dict2      ## 结果文件
defaultdict(<class 'int'>, {'a': 3, 'b': 1, 'c': 1, 'd': 5, 'e': 1, 'f': 2, 'g': 3})
>>> for i,j in dict2.items():       
...     print(i,j)
...
a 3
b 1
c 1
d 5
e 1
f 2
g 3

 

参考:https://blog.csdn.net/weixin_36383252/article/details/114910657

 

posted @ 2022-11-15 23:24  小鲨鱼2018  阅读(73)  评论(0编辑  收藏  举报