0
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?

Rohan
  • 55
  • 6
  • What is your actual question about this code? – Klaus D. May 03 '20 at 11:45
  • How the values are being stored in the d3 dictionary? Do the values being stored are the d1 and d2 dictionaries as the whole or one-by-one the key:value pairs of the dictionaries? – Rohan May 03 '20 at 11:56
  • The code is very simple. It contains only two relevant straight forward lines. Could you be more clear which part it is that you have troubles understanding? – Klaus D. May 03 '20 at 12:01
  • There are several high rated answers to this https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python/26853961#26853961 – Joe May 03 '20 at 12:04
  • https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python/38990#38990 – Joe May 03 '20 at 12:04
  • https://stackoverflow.com/questions/20656135/python-deep-merge-dictionary-data – Joe May 03 '20 at 12:05
  • https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries – Joe May 03 '20 at 12:05

1 Answers1

0

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)
Gabio
  • 9,126
  • 3
  • 12
  • 32
  • Dictionaries have a `copy` method that produces a shallow copy, so you do not need to import `copy`. – Booboo May 03 '20 at 12:12
  • @Booboo you're right! I thought at first to use deepcopy but I didn't want to confuse the OP. Thanks for your feedback! – Gabio May 03 '20 at 12:16