본문 바로가기
Python

[Python] defaultdict in collections

by llHoYall 2021. 5. 1.

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.

'Python' 카테고리의 다른 글

[Python] Counter in collections  (0) 2021.05.01
[Python] OrderedDict in collections  (0) 2021.05.01
[Python] deque in collections  (0) 2021.04.30
[Python] Underscore Usage  (0) 2021.04.26
[Flask] Using Markdown on Flask  (0) 2021.03.01

댓글