【发布时间】:2021-09-12 21:18:26
【问题描述】:
我有一本原始字典 - student = {"name":"Mike","class":{"grade":10,"section":"b"}}。现在,我有另一个new_dict = {"class":{"grade":10, "section":"c"}}
现在,我想用 new_dict 更新我的学生字典以匹配键,student.update(new_dict) 工作正常。但是我可能遇到new_dict = "class":{"section":"d"} 之类的情况,当我提供更新时,它会更新学生的字典,而"grade":10 会丢失。
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'}}
在这种情况下进行更新的最佳方法是什么,在所有键和条目中更新并仅更新匹配的键和值(即使它在嵌套内部)。
【问题讨论】:
标签: python dictionary