Merge two dictionaries


PHOTO EMBED

Tue Mar 31 2020 05:32:45 GMT+0000 (UTC)

Saved by @EnjoyByte #python #python #dictionary #mergedictionary #dict

 
def merge_two_dicts(a, b):
 
 
   c = a.copy()   # make a copy of a
 
   c.update(b)    # modify keys and values of a with the ones from b
 
   return c
 
 
 
 
 
a = { 'x': 1, 'y': 2}
 
b = { 'y': 3, 'z': 4}
 
 
print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}
 
 
content_copyCOPY

In python, the dictionary class provides a function update(). It accepts an another dictionary or an iterable object(collection of key value pairs) as argument. Then merges the contents of this passed dictionary or Iterable in the current dictionary.