0

I have a original dictionary - student = {"name":"Mike","class":{"grade":10,"section":"b"}}. Now, I have another new_dict = {"class":{"grade":10, "section":"c"}}

Now, i wanted to update my student dict with new_dict for matching key, student.update(new_dict) works fine. But I could have cases like new_dict = "class":{"section":"d"} and when i give update, it updates the student dict and "grade":10 goes missing.

student = {"name":"Mike","class":{"grade":10,"section":"b"}}
new_dict = {"class":{"section":"c"}}
student.update(new_dict)

Actual output:
=============
print(student)
{'name': 'Mike', 'class': {'section': 'c'}}

Expected output:
================
{'name': 'Mike', 'class': {"grade":10,'section': 'c'}}

What is the best way to do an update in this case, update inside all keys and entries and update only the matching key and value(even if it's inside nested).

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
user9763248
  • 35
  • 1
  • 5

1 Answers1

0

Maybe you could iterate over the new_dict and update inside the elements instead.

student = {"name":"Mike","class":{"grade":10,"section":"b"}}
new_dict = {"class":{"section":"c"}}


for k, v in new_dict.items():
    student[k].update(v)
Chris
  • 15,819
  • 3
  • 24
  • 37