Python/모듈

[Python] 딕서너리 한번에 초기화 하는 방법 (defaultdict 사용 방법)

yejunpark 2023. 8. 6. 16:09

defaultdict

defaultdict는 value 지장 하지 않은 key의 값을 0으로 갖습니다.

예시

예를 들어 Hello, world!라는 문장에서 각 알파벳이 몇 번 사용되었는지 구하는 문제가 있다고 가정하겠습니다.

dict를 이용한 풀이

text = “Hello, world!”

d = dict()
for c in text:
    if c not in d.keys():
        d[c] = 0
    d[c] += 1

print(d)

defaultdict를 이용한 풀이

from collections import defaultdict

text = “Hello, world!”

d = defaultdict(int)
for c in text:
    d[c] += 1

print(dict(d))

두 풀이의 차이점

dict를 이용하여 문제를 풀 경우 딕셔너리에 키 값이 있는지 확인하고 초기화하는 작업이 필요합니다.

if c in d.keys():
    d[c] = 0

만약 이 과정을 진행하지 않는다면 `KeyError` 오류가 발생합니다.

하지만 defaultdict를 이용하면 딕셔너리의 값을 0으로 초기화해 주기 때문에 위 과정이 필요하지 않습니다.

사용 방법

defaultdictcollections의 하위 클래스입니다.

from collections import defaultdict

defaultdict는 인수로 자료형을 받습니다. 위 예시의 경우 defaultdict(int)로 이 경우에는 0으로 자동 초기화 됩니다.

자세한 내용은 다음 링크를 참고해 주세요!
https://docs.python.org/ko/3/library/collections.html#collections.defaultdict

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.,,...

docs.python.org

정리

위 예시처럼 집계를 하는 문제를 dict를 이용하여 풀면 초기값을 신경 써야 하는 문제가 있습니다. 이와 같은 경우 defaultdict를 이용하면 이러한 불편을 피할 수 있습니다.