👄 Language/Python

[Python] 파이썬 유사 딕셔너리 defaultdict에 대해 알아보기

Nyan cat 2022. 9. 29. 16:33

📌  defaultdict란?

defaultdict는 collections 모듈에 내장된 유사 딕셔너리로 딕셔너리를 만드는 클래스인 dict의 서브클래스이다.

파이썬의 기존 딕셔너리와 다른 점은 key값이 없을 경우 지정해둔 디폴트값을 반환한다는 점이다.

아래 파이썬 공식 문서를 참조하면 더 자세한 정보를 알 수 있다.

https://docs.python.org/3/library/collections.html#collections.defaultdict

 

collections — Container datatypes — Python 3.10.7 documentation

collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() factory f

docs.python.org

import collections

# key 값이 없을 경우 기본값을 지정해주는 함수
def default_factory():
    return "no_value"

# 라이브러리를 만들어서 defaultdict로 선언하면서 값을 할당
test_dict = collections.defaultdict(default_factory, a = 1, b = 2)

print(test_dict)
print(test_dict['a'])
print(test_dict['c'])

# 결과값
# defaultdict(<function default_factory at 0x7ff42ef396a8>, {'a': 1, 'b': 2})
# 1  -> a에 1이라는 값이 할당 되있어서 할당된 값 출력
# no_value -> c라는 key가 없어서 default_factory에 따라 no_value 출력

 

💧 참고

기본 dictionary에도 유사한 기능(dict.setdefault)이 있다.

반응형