[Better Way #17] 내부 상태에서 원소가 없는 경우를 처리할 때는 setdefault 보다 defaultdict를 사용하라
본문은 “파이썬 코딩의 기술 (Effective Python, 2판)”의 “Chapter 02. List and Dictionary”을 읽고 정리한 내용입니다.
collections
내장 모듈에 있는defaultdict
클래스는 키가 없을 때 자동으로 디폴트 값을 저장해 딕셔너리를 다룰 때 키가 없는 경우를 쉽게 처리할 수 있다.1 2 3 4 5 6 7 8 9 10 11 12 13 14
from collections import defaultdict class Visits: def __init__(self): self.data = defaultdict(set) def add(self, country, city): self.data[country].add(city) visits = Visits() visits.add("영국", "버스") visits.add("영국", "런던") print(visits.data) # defaultdict(<class 'set'>, {'영국': {'런던', '버스'}})
- 임의의 키가 들어있는 딕셔너리가 어떻게 생성되었는지 모르는 경우, 딕셔너리의 원소에 접근하려면 우선
get
을 사용해야 한다. - 하지만
setdefault
가 더 짧은 코드를 만들어내는 몇 가지 경우에는setdefault
를 사용하는 것도 고려해볼 수 있다.
This post is licensed under CC BY 4.0 by the author.