Problem
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4}
일때, a와 b를 합친 값
c = {'a': 3, 'b': 2, 'c': 3, 'd': 4}
을 구하고자 한다. 같은 키가 존재하면 연산을, 키가 존재하지 않으면 병합하는 과정이 필요하다.
Solution
collections.Counter를 사용하면 된다. 단, 모든 value 값은 int 형이어야 한다.
from collections import Counter
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4}
c = Counter(a) + Counter(b)
#출력결과
Counter({'a': 3, 'b': 2, 'c': 3, 'd': 4})
만약 딕셔너리를 리턴해야할 경우 연산 결과를 dict로 감싸주면 된다.
from collections import Counter
a = {'a': 1, 'b': 2, 'c': 3}
b = {'a': 2, 'd': 4}
c = dict(Counter(a) + Counter(b))
#출력결과
{'a': 3, 'b': 2, 'c': 3, 'd': 4}
'Python' 카테고리의 다른 글
[Python] 딕셔너리의 키와 기본 값을 저장하기 (0) | 2022.03.24 |
---|---|
[Python] 문자열 리스트를 정수 리스트로 변환 (0) | 2022.03.24 |
[Python] requests User-Agent 설정하기 (0) | 2021.12.28 |
[Python] list, set, dict, tuple (0) | 2021.12.22 |
[Python] Dictionary get value from key (0) | 2021.12.22 |