DevLog

[Python] defaultdict() - 딕셔너리에 디폴트 value 초깃값 설정하기 본문

프로그래밍 언어/Python

[Python] defaultdict() - 딕셔너리에 디폴트 value 초깃값 설정하기

김만콩 2024. 8. 5. 17:29

defaultdict란?

딕셔너리와 유사한 자료구조.
value의 디폴트 값을 미리 지정하여 key를 저장할 때 따로 value를 작성하지 않아도 오류 없이 요소를 생성해준다.

ex) `defaultdict(int)` => 0으로 초기화
      `defaultdict(list)` => 빈 리스트 [ ]로 초기화

from collections import defaultdict

dic1 = defaultdict(int)
dic1['a'] # 새로운 키 -> 값을 0으로 초기화

# 결과
defaultdict(<class 'int'>, {'a':0})
from collections import defaultdict

dic2 = defaultdict(list)
dic2['a'] # 새로운 키 -> 값을 빈 리스트로 초기화

# 결과
defaultdict(<class 'list'>, {'a':[]})

+) 예시 코드

# n개의 튜플 (a, b, c)를 입력받아 딕셔너리에 a를 key, (b, c)를 value로 하여 저장하는 경우

from collections import defaultdict

n = int(input())
record = defaultdict(list) # 리스트로 디폴트값 설정

for _ in range(d):
    a, b, c = map(int, input().split())
    record[a].append((b, c)) # 빈 리스트 생성 없이 바로 append 가능
    
print(record)


# 결과
defaultdict(<class 'list'>, {1: [(1, 1), (4, 1), (3, 4), (2, 2)], 3: [(1, 3)], 2: [(1, 5), (2, 7)]})

일반 딕셔너리 자료구조를 사용하는 경우엔 키에 따른 value의 값을 각각 설정해줘야 한다.
반대로 `defaultdict`를 사용하는 경우에는 저장하려는 키가 딕셔너리 내에 없다면 디폴트 값으로 자동 초기화를 제공하기 때문에 value의 초기화 과정 없이 비교적 간단하게 코드를 작성할 수 있다.