python 中 collections 模块中的 defaultdict

 

01、

[root@pc1 test1]# python3
Python 3.11.4 (main, Jul  5 2023, 14:15:25) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict   ## 引入该模块
>>> dict1 = defaultdict(int)              ## 生成数字字典
>>> dict2 = dict()
>>> dict1
defaultdict(<class 'int'>, {})
>>> dict2
{}
>>> dict1["aa"] += 5        ## 默认数字字典可以直接进行数值运算
>>> dict1
defaultdict(<class 'int'>, {'aa': 5})
>>> dict2["aa"] += 5        ## 一般字典不可以
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'aa'
>>> dict2
{}

 

 

。 

 

posted @ 2023-10-13 16:09  小鲨鱼2018  阅读(13)  评论(0编辑  收藏  举报