
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Combine two dictionary adding values for common keys
When analyzing data with python we come across situations when we have to merge two dictionaries in such a way that we add the values of those elements whose keys have equal values. In this article we will see such two dictionaries getting added.
With For loop and | Operator
In this approach we design a for loop to check for the presence of the value of the key in both the dictionaries and then add them. Finally we merge the two dictionaries using the | operator available for the dictionaries.
Example
dictA = {'Mon': 23, 'Tue': 11, 'Sun': 6} dictB = {'Wed': 10, 'Mon': 12, 'Sun': 4} # Add with common key for key in dictB: if key in dictA: dictB[key] = dictB[key] + dictA[key] else: pass res = dictA | dictB print(res)
Running the above code gives us the following result −
Output
{'Mon': 35, 'Tue': 11, 'Sun': 10, 'Wed': 10}
Using Counter
The Counter function from the Collections module can be directly applied to merge the two dictionaries which preserves the keys. And in turn adds the values at the matching keys.
Example
from collections import Counter dictA = {'Mon': 23, 'Tue': 11, 'Sun': 6} dictB = {'Wed': 10, 'Mon': 12, 'Sun': 4} res = Counter(dictA) + Counter(dictB) print(res)
Running the above code gives us the following result −
Output
Counter({'Mon': 35, 'Tue': 11, 'Sun': 10, 'Wed': 10})
- Related Articles
- C# Program to combine Dictionary of two keys
- Keys associated with Values in Dictionary in Python
- Append Dictionary Keys and Values (In order ) in dictionary using Python
- How to Common keys in list and dictionary using Python
- How to convert Python dictionary keys/values to lowercase?
- Find keys with duplicate values in dictionary in Python
- How to insert new keys/values into Python dictionary?
- Python – Limit the values to keys in a Dictionary List
- How to create Python dictionary from list of keys and values?
- How to split Python dictionary into multiple keys, dividing the values equally?
- Properties of Dictionary Keys in Python
- Python Extract specific keys from dictionary?
- Python - Cumulative Mean of Dictionary keys
- How does Python dictionary keys() Method work?
- Python dictionary with keys having multiple inputs
