Home >Backend Development >Python Tutorial >How Can I Efficiently Merge Python Dictionaries and Sum Values for Common Keys?

How Can I Efficiently Merge Python Dictionaries and Sum Values for Common Keys?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 16:22:15717browse

How Can I Efficiently Merge Python Dictionaries and Sum Values for Common Keys?

Merging Dictionaries in Python: Adding Values for Overlapping Keys

When working with multiple dictionaries, it's often necessary to combine them in a meaningful way. One common scenario involves adding the values of keys that appear in both dictionaries while keeping keys that only exist in one.

Problem:

Consider the following dictionaries:

Dict A: {'a': 1, 'b': 2, 'c': 3}
Dict B: {'b': 3, 'c': 4, 'd': 5}

The goal is to merge these dictionaries such that the result is:

{'a': 1, 'b': 5, 'c': 7, 'd': 5}

Solution Using Collections.Counter:

A Pythonic and efficient way to achieve this is by using the collections.Counter class. It's a subclass of dict that provides a convenient way to do element-based counting, which lends itself well to the task of merging dictionaries.

from collections import Counter

A = Counter({'a':1, 'b':2, 'c':3})
B = Counter({'b':3, 'c':4, 'd':5})

To merge the dictionaries, we simply add the Counter objects:

merged_dict = A + B

The result is a new Counter object, which automatically adds values for overlapping keys:

merged_dict.most_common()
# Output: [('c', 7), ('b', 5), ('d', 5), ('a', 1)]

Converting it to a regular dictionary is trivial:

merged_dict = dict(merged_dict)

The above is the detailed content of How Can I Efficiently Merge Python Dictionaries and Sum Values for Common Keys?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn