본문 바로가기
Dev/Algorithm

Defaultdict 사용하기

by jusep 2025. 8. 7.

defaultdict란?

defaultdict는 Python의 collections 모듈에 포함된 클래스입니다. 일반적인 딕셔너리(dict)와 비슷하지만, 키가 존재하지 않을 때 기본값을 제공하는 기능을 추가로 제공합니다. 이를 통해 키가 없는 경우 KeyError를 발생시키는 대신, 지정된 기본값을 반환하거나 새로운 키-값 쌍을 자동으로 생성합니다.

defaultdict는 첫 번째 인자로 기본값을 생성하는 팩토리 함수를 받습니다. 예를 들어, int, list, set 등을 팩토리로 사용할 수 있습니다. 키에 접근할 때 해당 키가 없으면 팩토리 함수가 호출되어 기본값이 생성됩니다.


defaultdict의 동작 방식

  • 일반 dict:
     
    d = {}
    d['key'] += 1 # KeyError 발생: 'key'가 없기 때문
     
  • defaultdict:여기서 d['key']에 처음 접근할 때, defaultdict(int)int()를 호출해 기본값 0을 생성하고, 그 값을 증가시켜 1을 저장합니다.
     
    from collections import defaultdict
    d = defaultdict(int) # 기본값은 int() -> 0
    d['key'] += 1 # 'key'가 없으면 0으로 초기화 후 +1
    print(d) # 출력: defaultdict(<class 'int'>, {'key': 1})
     

언제 defaultdict를 사용하나?

defaultdict는 딕셔너리에서 키가 없는 경우 기본값이 필요한 상황에서 유용합니다. 아래는 주요 사용 사례입니다:

  1. 카운팅 (빈도수 계산):
    • 문자열, 리스트 등의 요소 빈도를 셀 때.
    • 예: 문자열에서 각 문자의 빈도를 계산.
      python
       
      from collections import defaultdict
      s = "apple"
      counter = defaultdict(int)
      for char in s:
      counter[char] += 1
      print(counter) # 출력: defaultdict(<class 'int'>, {'a': 1, 'p': 2, 'l': 1, 'e': 1})
  2. 그룹화:
    • 데이터를 키에 따라 그룹화할 때, 리스트나 집합을 기본값으로 사용.
    • 예: 카테고리별로 값을 리스트로 저장.
      python
       
      from collections import defaultdict
      data = [('fruit', 'apple'), ('fruit', 'banana'), ('vegetable', 'carrot')]
      grouped = defaultdict(list)
      for category, item in data:
      grouped[category].append(item)
      print(grouped) # 출력: defaultdict(<class 'list'>, {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']})
  3. 누적합 또는 상태 관리:
    • 특정 상태를 키로 사용해 값을 누적할 때.
    • 예: 이전 질문의 도로 구간 문제에서 상태별 빈도를 저장.
      python
       
      from collections import defaultdict
      state_count = defaultdict(int)
      state_count[(0, 0, 0, 0)] = 1 # 초기 상태
  4. 중첩 딕셔너리:
    • 다차원 딕셔너리에서 키가 없어도 자동으로 중첩 구조 생성.
      python
       
      from collections import defaultdict
      nested = defaultdict(lambda: defaultdict(int))
      nested['a']['b'] += 1 # 자동으로 {'a': {'b': 1}} 생성

댓글