Python
[Python] defaultdict in collections
llHoYall
2021. 5. 1. 17:31
defaultdict is a subclass of the built-in dict class.
dict returns KeyError if you get value with nonexistence key.
In contrast, defaultdict returns default value even with the nonexistence key.
Usage
Default Value with Built-in Class
from collections import defaultdict
d = defaultdict(int)
d['apple'] = 3
print(d['banana'])
# 0
print(d)
# defaultdict(<class 'int'>, {'apple': 3, 'banana': 0})
Default Value with User-defined Function
from collections import defaultdict
def return_one():
return 1
d = defaultdict(return_one)
d['apple'] = 3
print(d['banana'])
# 1
print(d)
# defaultdict(<function return_one at 0x7f4c28d4a1f0>, {'apple': 3, 'banana': 1})
Default Value with Lambda Function
from collections import defaultdict
d = defaultdict(lambda: "zero")
d['apple'] = "four"
print(d['banana'])
# zero
print(d)
# defaultdict(<function <lambda> at 0x7fb47ea501f0>, {'apple': 'four', 'banana': 'zero'})
Conclusion
Although defaultdict is almost identical to dict, there is a difference that when a non-existent key is used, the key is registered with a defined default value.
반응형