Python : Merge Dictionaries

Merging dictionaries using update function

Function Parameter Synatax Description
update iterable dictionary . update ( iterable ) Insert items into a dictionary specified by an iterable object with key value pairs

Note : In case of identical keys in the iterable, the final value will be taken from the iterable.

Below program uses update function to merge the content of dictionary ( add_on_2 ) into dictionary ( add_on_1 ).

Python3

main = { 'Netflix' : 10, 'Amazon_Prime' : 20 }
add_on_1 = { 'HotStar' : 5, 'Fox_Sports' : 5, 'BBC' : 3, 'Disney' : 12 }
add_on_2 = { 'Sky_Sports' : 7, 'ESPN' : 8, 'HBO' : 13, 'HotStar' : 6 }

print ("Main : " + str(main))
print ("Add On 1 : " + str(add_on_1))
print ("Add On 2 : " + str(add_on_2))

add_on_1.update(add_on_2)
print ("\nMerging (Add on 1) and (Add on 2) in (Add on 1) using update function.\n")

print ("Main : " + str(main))
print ("Add On 1 : " + str(add_on_1))
print ("Add On 2 : " + str(add_on_2))

Output

Main : {'Netflix': 10, 'Amazon_Prime': 20}
Add On 1 : {'HotStar': 5, 'Fox_Sports': 5, 'BBC': 3, 'Disney': 12}
Add On 2 : {'Sky_Sports': 7, 'ESPN': 8, 'HBO': 13, 'HotStar': 6}

Merging (Add on 1) and (Add on 2) in (Add on 1) using update function.

Main : {'Netflix': 10, 'Amazon_Prime': 20}
Add On 1 : {'HotStar': 6, 'Fox_Sports': 5, 'BBC': 3, 'Disney': 12, 'Sky_Sports': 7, 'ESPN': 8, 'HBO': 13}
Add On 2 : {'Sky_Sports': 7, 'ESPN': 8, 'HBO': 13, 'HotStar': 6}


Copyright (c) 2019-2021, Algotree.org.
All rights reserved.