Algorithm

[Python] defaultdict 딕셔너리 기본값 설정하는 방법

띵지니어 2023. 6. 21. 14:14

 

딕셔너리에 대한 문제 해결을 하면서 keyError를 처리하기 위해, key 값과 value 값을 넣어서 초기화를 해준 기억이 있다.

대표적으로 문자열에서의 쓰인 알파벳 개수를 판단하기 위해 사용하면 편리하다.

"hello world" 라는 문장에서 각 알파벳의 개수를 딕셔너리 형태로 나타내고 싶을 때, 나는 보통 아래처럼 표현 하였다.

str = "hello world"

d = dict()
for i in str:
    if i not in d:
        d[i] = 0
    d[i] += 1

print(d)

# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

 

if i not in d:
    d[i] = 0

for문 안에 이 코드가 존재하는 이유는 딕셔너리에 key가 없으면 KeyError가 발생하기 때문에, 원하는 key와 value를 넣어서 초기화해줘야 했었다.


 

⭐️ defaultdict 생성

하지만 defaultdict을 사용한다면, 초기화를 할 필요가 없을뿐더러 없는 key에도 기본값(default_factory)을 주어 접근이 가능하다.

정의 : class collections.defaultdict(default_factory=None/[...])

default_factory int로 설정하면 defaultdict를 세는(counting) 데 유용하게 사용할 수 있다.

from collections import defaultdict

str = "hello world"

d = defaultdict(int)
for i in str:
    d[i] += 1

print(d)
print(d['h'])

# defaultdict(<class 'int'>, {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# 1

 

 

⭐️ 없는 키 값을 호출하는 경우

from collections import defaultdict

str = "hello world"

d = defaultdict(int)
for i in str:
    d[i] += 1

print(d['a']) # d 에는 'a' 라는 key가 존재하지 않음

# 0

 

글자가 처음 발견될 때, 딕셔너리에서 누락되었으므로 default_factory 함수는 int()를 호출하여 기본 값 0을 제공한다.

항상 0을 반환하는 함수 int()는 상수 함수의 특별한 경우일 뿐이기 때문에,

상수 함수를 만드는 더 빠르고 유연한 방법은 (단지 0이 아니라) 임의의 상수값을 제공할 수 있는 람다 함수를 사용하면 된다.

 

 

⭐️ 람다함수로 기본값 설정 하는 방법

from collections import defaultdict

d = defaultdict(lambda: 'default value')
print(d['a'])

# default value

 

🔥 defaultdict의 기본값 설정에서의 인수로는 int 말고도 str, list, set 등 다른 자료형을 넣을 수도 있다.

 

참고  - 공식문서