Sometimes when you access a key in a dictionary , Key may not exist , So it needs to be checked , If no default value is found, it is sometimes necessary to add a default value .
A one-step approach is to use collections In bag defaultdict, It creates a dictionary that automatically sets the default values , Returns the value of the key if it exists , If the key does not exist, the default value is returned and the key value pair is added to the dictionary .
defaultdict The parameter to be passed in is a function , If it is int Then the initial value is 0, If it is list The initial value is an empty list , Of course, you can also pass in custom functions .
from collections import defaultdict
adict=defaultdict(int)
adict['a']=2
print(adict)
print(adict['b'])
print(adict)
bdict=defaultdict(lambda :'hhh')
print(bdict['c'])
Output :
defaultdict(<class 'int'>, {
'a': 2})
0
defaultdict(<class 'int'>, {
'a': 2, 'b': 0})
hhh
You can find , It is similar to the dictionary setdefault Very similar , But it saves more space , For example, to set the default value to an empty list ,setdefault The way to write is xxdict.setdefault(xxkey,[])
, No matter what xxkey Whether there is , Empty lists are created , But if you use xxdict=defaultdict(list)
, The empty list will be created only when the key cannot be found , So it saves more space .
defaultdict On initialization , You can also pass in the initial dictionary through the second parameter :
cdict=defaultdict(list,{
'c':'aaa'})
print(cdict)
Output :
defaultdict(<class 'list'>, {
'c': 'aaa'})