Python
[Python] 두 딕셔너리의 합 구하기
torimuk
2022. 2. 8. 13:33
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}