Notice
Recent Posts
Recent Comments
Link
오늘도 개발
setdefault와 defaultdict 본문
딕셔너리를 사용할 때 존재하지 않는 키에 값을 할당하면 오류가 난다.
setdefault나 defaultdict를 사용하면 이 때 새로운 키를 만들어 값을 할당하게 세팅할 수 있다.
(= setdefault, defaultdict는 딕셔너리의 기본값을 설정할 수 있게 해준다)
1. 일반적인 처리
1) 딕셔너리 선언
2) letter로 된 키가 딕셔너리에 없으면 키 생성후 1 할당
3) letter로 된 키가 딕셔너리에 있으면 해당 키에 1 추가
ref = {}
for letter in 'abxab':
if letter not in ref:
ref[letter] = 0
ref[letter] += 1
print(ref)
# {'a': 2, 'b': 2, 'x': 1}
2. setdefault
1번보다 가독성을 높일 수 있다.
하지만 매번 ref.setdefault(letter, 0)이 호출된다.
ref = {}
for letter in 'abxab':
ref.setdefault(letter, 0)
ref[letter] += 1
print(ref)
# {'a': 2, 'b': 2, 'x': 1}
3. defaultdict
for문 시작 전 기본값을 세팅해둘 수 있는 방법이다.
defaultdict()의 인수로는 함수를 넣는다.
기본값으로 0을 세팅하는 경우:
from collections import defaultdict
ref = defaultdict(int)
# int()는 0을 반환하므로, 키의 기본값이 0으로 세팅된다.
# ref = defaultdict(lambda: 0)으로 작성해도 된다.
for letter in 'abxab':
ref[letter] += 1
print(ref)
# {'a': 2, 'b': 2, 'x': 1}
기본값으로 빈 리스트를 세팅하는 경우:
from collections import defaultdict
ref = defaultdict(list)
words = ['abcd', 'abc', 'bcde']
for word in words:
ref[len(word)].append(word)
print(ref)
# {4: ['abcd', 'bcde'], 3: ['abc']}
참고
[파이썬] 사전의 기본값 처리 (dict.setdefault / collections.defaultdict)
'웹 프로그래밍 > Python3' 카테고리의 다른 글
| pytest 사용법 1) 설정, fixture, parametrize (0) | 2023.01.18 |
|---|---|
| pyenv와 pyenv-virtualenv (0) | 2023.01.03 |
| Python의 GC(Garbage Collection) (0) | 2022.10.31 |
| Global Interpreter Lock(GIL) (0) | 2022.10.29 |
| Asyncio와 비동기 작업 4) multithreading과 run_in_executor 메서드 (0) | 2022.08.30 |