Home > Backend Development > Python Tutorial > How Can I Pythonically Combine Two Dictionaries, Summing Values for Common Keys?

How Can I Pythonically Combine Two Dictionaries, Summing Values for Common Keys?

Susan Sarandon
Release: 2024-12-10 17:23:16
Original
232 people have browsed it

How Can I Pythonically Combine Two Dictionaries, Summing Values for Common Keys?

Combining Two Dictionaries Pythonically

Often, when working with dictionaries in Python, we need to merge multiple dictionaries into a single one. A common requirement in such scenarios is to combine the dictionaries, adding values for keys that appear in both.

For instance, consider the following two dictionaries:

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

Our goal is to merge these dictionaries to obtain the following result:

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

In other words, if a key appears in both dictionaries, their values should be summed up, while keys that exist only in one dictionary should retain their original values.

An elegant way to achieve this in Python is by leveraging the Counter class from the collections module:

from collections import Counter

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

The Counter class extends the functionality of a dictionary by providing an easy way to track the number of occurrences (counts) of values. In our case, we create Counter objects for both dictionaries, and then use the operator to combine them. The result is a new Counter object where the counts for matching keys are accumulated. Converting the Counter object back to a dictionary gives us the desired combined dictionary.

The above is the detailed content of How Can I Pythonically Combine Two Dictionaries, Summing Values for Common Keys?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template