Reputation: 321
Hi there I created a (what I call) nested dictionary:
gradeDict = {
"Intro to Programming":{
"student":{
"firstname":"Mike",
"lastname":"Miller",
"marks":{
"PS01":70,
"PS02":80
}
}
}
}
print(gradeDict['Intro to Programming']['student']['marks'])
which after asking for the values in key 'marks' gives the values
{'PS01': 70, 'PS02': 80}
That's perfect. Now I want add a NEW (key,value) pair to the superior key 'marks':
gradeDict.update( {"Intro to Programming":{ "student":{ "firstname":"Mike",
"lastname":"Miller","marks":{ "PS03":10}}}} )
print(gradeDict['Intro to Programming']['student']['marks'])
Unfortunately this gives
{'PS03': 10}
which I don't understand, a key should only be overwritten if it already exists, otherwise appended. 'marks' exists, but 'PS03' doesn't. What am I missing here, or how to get the desired entry:
{'PS01': 70, 'PS02': 80, 'PS03': 10}
Thanks a lot...
Upvotes: 1
Views: 47
Reputation: 24038
Good reasoning, but dict.update
doesn't exactly work like that. It doesn't recursively check each element, instead it sees that the key "Intro to Programming"
already exists in the first layer so it overwrites its value with {"student":{ "firstname":"Mike", "lastname":"Miller","marks":{ "PS03":10}}}
.
See this demonstration:
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)
Output:
{'Intro to Programming': {'NEW VALUE': {'firstname': 'Mike', 'lastname': 'Miller', 'marks': {'PS03': 10}}}}
If you want that kind of recursive updating, a quick Google search found for example this (adapted to work with Python 3, not tested extensively):
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)
Output:
{'Intro to Programming': {'student': {'firstname': 'Mike', 'lastname': 'Miller', 'marks': {'PS01': 70, 'PS02': 80, 'PS03': 10}}}}
Upvotes: 1