-
collections - defaultdict파이썬 Study/라이브러리 2021. 3. 11. 22:33
출처 :
https://excelsior-cjh.tistory.com/95
■ defaultdict
- 딕셔너리 dict와 거의 유사,
- key 값이 존재하지 않는 경우, default 함수 / object return 등의 기능을 수행할 수 있다
- nested default dict / class default dict 등으로 nested dictionary 구현 가능
→ 3단 이상은 class로 container 구현하는 것이 더 '구현하기' 좋음
1) 정의 :
- collections.defaultdict( < function when invalid key >, key=value, ... )
- 기본 key=value 쌍으로 initial 값 설정
- Key Error에 대해 수행할 함수와 return 값 설정 가능
- function 자리 : lambda, 기본 함수, set, list, dict 등을 넣어줄 수 있음
2) 작동 방식 :
import collections def default_factory(): return 'null' ex2 = collections.defaultdict(default_factory, a=1, b=2) # -> key없을 시 return 해줌 print(ex2) print(ex2['c']) # 존재하지 않아야 하지만, 'null' return >>> defaultdict(<function default_factory at 0x10ab50bf8>, {'b': 2, 'a': 1}) >>> 'null'
반응형'파이썬 Study > 라이브러리' 카테고리의 다른 글
re (regex - regular expression) (1) 2021.03.13 hashing (1) 2021.03.11 queue (1) 2021.03.11 heapq (1) 2021.03.11 list - instance (1) 2021.03.11