Today I Learned/Python & Pandas

파이썬 딕셔너리 모듈 (defaultdict, Counter)

하나719 2023. 8. 22. 17:32
반응형

파이썬에서 제공하는 딕셔너리 관련해서 편리한 모듈 세가지를 알아보자

 

1. defaultdict

딕셔너리에서 입력되지 않은 키로 조회하는 경우 에러가 발생하는데, defaultdict로 정의하면 입력되지 않은 키로 조회할 경우 default값으로 조회된다. 

 

defaultdict( 정의하고 싶은 디폴트 값 ) 

import collections

a = collections.defaultdict(int)
a['A'] # 출력 > 0

a = collections.defaultdict(float)
a['A'] # 출력 > 0.0

a = collections.defaultdict(bool)
a['A'] # 출력 > False

a = collections.defaultdict(str)
a['A'] # 출력  > ''

a = collections.defaultdict(lambda: 1)
a['A'] # 출력 > 1

a = collections.defaultdict(lambda: '하나')
a['A'] += '안녕' 
a['A'] # 출력 > '하나안녕'

2. Counter

아이템에 대한 개수를 계산해 딕셔너리로 반환 해준다.

 

import collections 

a = [0,1,1,2,2,2,4]
b = collections.Counter(a)
b

#출력 > Counter({0:1, 1:2, 2:3 ,4:0})

## 빈도 높은 항목 출력 
b.most_common(1)
#출력 [(2,3)]

b.most_common(2)
#출력 [(2,3), (1,2)]
반응형