简体   繁体   中英

Defaultdict not returning default values

d1 = defaultdict(lambda : defaultdict(lambda : defaultdict (lambda : 0)))
d1['first']['second'] = 2 #Assigning some value
d1['first']['third']   #Expecting to return the default value, which is 0, but ...
defaultdict(<function <lambda>.<locals>.<lambda>.<locals>.<lambda> at 0x7ff5765421e0>, {})

Why is this not returning 0?

Because there are three levels of defaultdict s until you reach the value 0 , so you need to do:

>>> d1['first']['second']['third']
0

You have 3 levels of defaultdict . So to get the default value you need 3 indexes.

print(d1[1][2][3])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM