[英]How to combine (append values) two nested dictionaries with the same keys in python?
[英]Combine two nested dictionaries with same keys but different dictionaries as values
我有兩個字典(參見代碼示例),其中嵌套字典作為值。 我想加入兩個字典,這樣我就可以獲得一個字典,在嵌套字典中添加了鍵值對。
我當前的代碼有效,但對我來說似乎並不枯燥(不要重復自己)。 解決這個問題的最pyhtonic方法是什么?
dictionary_base = {
'anton': {
'name': 'Anton',
'age': 29,
},
'bella': {
'name': 'Bella',
'age': 21,
},
}
dictionary_extension = {
'anton': {
'job': 'doctor',
'address': '12120 New York',
},
'bella': {
'job': 'lawyer',
'address': '13413 Washington',
},
}
for person in dictionary_base:
dictionary_base[person]['job'] = dictionary_extension[person]['job']
dictionary_base[person]['address'] = dictionary_extension[person]['address']
print(dictionary_base)
所需的輸出應如下所示
{'anton': {'address': '12120 New York',
'age': 29,
'job': 'doctor',
'name': 'Anton'},
'bella': {'address': '13413 Washington',
'age': 21,
'job': 'lawyer',
'name': 'Bella'}}
使用dict.update
前任:
dictionary_base = {
'anton': {
'name': 'Anton',
'age': 29,
},
'bella': {
'name': 'Bella',
'age': 21,
},
}
dictionary_extenstion = {
'anton': {
'job': 'doctor',
'address': '12120 New York',
},
'bella': {
'job': 'lawyer',
'address': '13413 Washington',
},
}
for person in dictionary_base:
dictionary_base[person].update(dictionary_extenstion[person])
print(dictionary_base)
輸出:
{'anton': {'address': '12120 New York',
'age': 29,
'job': 'doctor',
'name': 'Anton'},
'bella': {'address': '13413 Washington',
'age': 21,
'job': 'lawyer',
'name': 'Bella'}}
你可以使用字典理解:
{k: {**dictionary_base[k], **dictionary_extension[k]} for k in dictionary_base}
輸出:
{'anton': {'name': 'Anton',
'age': 29,
'job': 'doctor',
'address': '12120 New York'},
'bella': {'name': 'Bella',
'age': 21,
'job': 'lawyer',
'address': '13413 Washington'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.