Change language

Python | Combine two dictionaries adding values ​​for shared keys

| |

Example :

  Input:  dict1 = {’a’: 12,’ for’: 25, ’c’: 9} dict2 = {’Geeks’: 100,’ geek’: 200, ’for’: 300}  Output:  {’ for’: 325, ’Geeks’: 100,’ geek’: 200} 

Let’s see some of the methods to make the task.

Method # 1: Naive method

# Python program to combine two dictionaries
# add values ​​for shared keys
# initialize two dictionaries

dict1 = { ’a’ : 12 , ’for’ : 25 , ’c’ : 9 }

dict2 = { ’Geeks’ : 100 , ’geek’ : 200 , ’ for’ : 300 }

 

  
# adding values ​​with a shared key

for key in dict2:

if key in dict1:

dict2 [key] = dict2 [key] + dict1 [key]

else :

pass

 

print (dict2)

Exit:

 {’for’: 325, ’Geeks’: 100,’ geek’: 200} 

Method # 2: Using collections.Counter ()

# Python program to combine two dictionaries
# add values ​​for public keys

from collections import Counter

 
# initializing two dictionaries

dict1 = { ’a’ : 12 , ’for’ : 25 , ’c’ : 9 }

dict2 = { ’Geeks’ : 100 , ’geek’ : 200 , ’for’ : 300 }

 

 
# adding values ​​with a shared key

 

Cdict = Counter (dict1) + Counter (dict2)

print (Cdict)

Exit:

 Counter ({’ for’: 325, ’geek’: 200,’ Geeks’: 100, ’a’: 12,’ c’: 9}) 

Method # 3: Using itertools.chain()

# Python program to combine two dictionaries
# add values ​​for public keys

import itertools 

import collections

  
# initializing two dictionaries

dict1 = { ’ a’ : 12 , ’for’ : 25 , ’c’ : 9 }

dict2 = { ’ Geeks’ : 100 , ’geek’ : 200 , ’for’ : 300 }

  
# using defaultdict

Cdict = collections.defaultdict ( int )

 
# iterating key, val with string ()

for key, val in itertools. chain (dict1.items (), dict2.items ()):

Cdict [key] + = val

 

print ( dict (Cdict))

Exit:

 {’for’: 325,’ a’: 12, ’geek’: 200,’ Geeks’: 100, ’c’: 9}