Search code examples
pythonpython-3.xdictionarycpythonmergeddictionaries

Merging the dictionaries


d1 = {'Adam Smith':'A', 'Judy Paxton':'B+'}
d2 = {'Mary Louis':'A', 'Patrick White':'C'}
d3 = {}

for item in (d1, d2):
    d3.update(item)

print(d3)

In this Python Code, the task is to merge the dictionaries and assign the merged dictionaries to the third dictionary. They used the for loop aproach which is a bit confusing for me as I'm not able to understand the loop part.

Could you help me determine that loop-debugging part?


Solution

  • No loops needed. Just copy one of the dicts and update it with the second one:

    d1 = {'Adam Smith':'A', 'Judy Paxton':'B+'}
    d2 = {'Mary Louis':'A', 'Patrick White':'C'}
    d3 = d1.copy()
    d3.update(d2)
    print(d3)