我有两个字典(请参见代码示例),其中嵌套的字典为值。我想同时加入两个字典,以便在嵌套字典中获得一个带有附加键值对的单个字典。
我当前的代码有效,但是对我来说似乎不干(不要重复)。解决这个问题的最方法是什么?
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'}}
答案 0 :(得分:2)
使用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'}}
答案 1 :(得分:1)
您可以使用字典理解:
{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'}}