当前位置:网站首页>Easy to use dictionary -defaultdict

Easy to use dictionary -defaultdict

2022-06-25 02:54:00 Upward a Peng

Reference link :https://blog.csdn.net/sGDUTBMW/article/details/108962367

defaultdict Class is like a dict, But it is initialized with a type ;
defaultdict Class takes a type as an argument , When the accessed key does not exist , You can instantiate a value as the default ; If NULL .

Compared with dict, When the accessed key does not exist , No mistake. , Only one default value will be returned , besides , In the use of dict In the process of , identical key Only one... Can be saved value, When there is a repetition key when , Will be covered value, Not conducive to finding the same key Multiple value The situation of , and defaultdict You can return multiple value value .

Example :

 Insert picture description here
Output :
 Insert picture description here
defaultdict In addition to accepting the type name as an argument to the initialization function , You can also use any callable function without parameters , At that time, the return result of this function will be taken as the default value , This makes the default value more flexible

from collections import defaultdict

strings = ('puppy', 'kitten', 'puppy', 'puppy',
           'weasel', 'puppy', 'kitten', 'puppy')


def zero():
    return 0


connts = defaultdict(zero)  #  Use custom without parameters zero function 
counts = defaultdict(lambda: 0)  #  Use lambda To define simple functions , The effect same as above 

for s in strings:
    counts[s] += 1
print(counts)

Output :
 Insert picture description here

原网站

版权声明
本文为[Upward a Peng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206242349418878.html