[Python] Python collection defaultdict
in Python on Pandas, Collection, Defaultdict
Python Collection Default dict
python collections 이란?
python collections are specialized container datatypes providing alternatives to Python’s general purposd built-in conatiners dict,list,set and tuple
- python의 built-in type에 mechanisim이 추가됨
So What exactly is DefaultDict?
defaultdict
는 모든 일반적인 목적으로 만든dict
keyerror
를 일으키지 않음(일반적인 dict는 handling code를 작성해야하지만 내부에 이미 구현)defaultdict
는 다음 사항이 적용- access할때 dictionary에 key가 미존재시
keyerror
를 일으키지 않음 defaultdict
생성시 default value를 제공해서 자동으로 key가 생성되게함
- access할때 dictionary에 key가 미존재시
default value 생성
- 아래는
defaultdict
를 생성할때int, float and str
로 생성하는 예제a_dct = defaultdict(int) # The Default Value is "0" a_dct = defaultdict(float) # The Default Value is "0.0" a_dct = defaultdict(str) # The Default Value is ""
default value를 자동으로 조회 가능
list, tuple
로도 생성가능 (Using defaultdict with list)- key 존재유무와 상관없이
append
와 같은 list function을 사용가능
- key 존재유무와 상관없이
- extreamly careful about
defaultdict
를list, tuple, int, float
로 만들때 overwrite and assign (with totally different)가능, 이런 상황시 code fail