您好,我在那里创建了一个(我称之为)嵌套字典:
gradeDict = {
"Intro to Programming":{
"student":{
"firstname":"Mike",
"lastname":"Miller",
"marks":{
"PS01":70,
"PS02":80
}
}
}
}
print(gradeDict['Intro to Programming']['student']['marks'])
在询问关键“标记”中的值后给出的值
{'PS01': 70, 'PS02': 80}
那太完美了。现在,我想向上级键“ marks”添加一个新的(键,值)对:
gradeDict.update( {"Intro to Programming":{ "student":{ "firstname":"Mike",
"lastname":"Miller","marks":{ "PS03":10}}}} )
print(gradeDict['Intro to Programming']['student']['marks'])
不幸的是,这给了
{'PS03': 10}
我不理解,只有在密钥已经存在的情况下才应该覆盖它,否则将其附加。 “标记”存在,但“ PS03”不存在。我在这里缺少什么,或者如何获得所需的条目:
{'PS01': 70, 'PS02': 80, 'PS03': 10}
非常感谢...
答案 0 :(得分:1)
有充分的理由,但是dict.update
并非完全如此。它不会递归地检查每个元素,而是看到密钥"Intro to Programming"
已经存在于第一层中,因此它用{"student":{ "firstname":"Mike", "lastname":"Miller","marks":{ "PS03":10}}}
覆盖了它的值。
观看此演示
gradeDict = {
"Intro to Programming":{
"student":{
"firstname":"Mike",
"lastname":"Miller",
"marks":{
"PS01":70,
"PS02":80
}
}
}
}
gradeDict.update(
{"Intro to Programming": {"NEW VALUE": {"firstname": "Mike", "lastname": "Miller","marks": {"PS03": 10}}}}
)
print(gradeDict)
输出:
{'Intro to Programming': {'NEW VALUE': {'firstname': 'Mike', 'lastname': 'Miller', 'marks': {'PS03': 10}}}}
如果您希望进行这种递归更新,可以快速进行Google搜索found for example this(适用于Python 3,未经广泛测试):
from collections.abc import Mapping
def dict_merge(dct, merge_dct):
for k, v in merge_dct.items():
if (k in dct and isinstance(dct[k], dict)
and isinstance(merge_dct[k], Mapping)):
dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]
gradeDict = {
"Intro to Programming":{
"student":{
"firstname":"Mike",
"lastname":"Miller",
"marks":{
"PS01":70,
"PS02":80
}
}
}
}
dict_merge(gradeDict, {"Intro to Programming": {"student": {"firstname": "Mike", "lastname": "Miller","marks": {"PS03": 10}}}})
print(gradeDict)
输出:
{'Intro to Programming': {'student': {'firstname': 'Mike', 'lastname': 'Miller', 'marks': {'PS01': 70, 'PS02': 80, 'PS03': 10}}}}