[Python] defaultdict 함수의 초깃값을 defaultdict로 초기화하기

2024. 1. 8. 16:48Memorizing/Python

728x90

python의 collections 라이브러리에서는 defaultdict라는 함수를 제공하는데, defaultdict는 초깃값(e.g. int, float, list, dict)을 지정하면, 그 초깃값을 이용하여 dict의 초기화를 시켜주게됩니다. 

하지만, 경우에따라 defaultdict의 초깃값을 defaultdict로 초기화해야하는 경우가 생기는데, 이런 경우 어떻게 할 수 있을까요 ? 아래와 같이 lambda함수를 사용하면 defaultdict의 초깃값을 defaultdict로 초기화할 수 있습니다.

import collections
dictionary = collections.defaultdict(lambda x: collections.defaultdict(int))