我正在尝试合并两个嵌套字典,这些字典将通过比较值来合并不同的字典。如果键相同,则将其替换为最近的值。
我正在使用always_merger.merge()进行合并,但会追加其他元素。它应该比较值并将其替换为最近的值。
dictionary_1 = dict([('modifyParameterReq', {
'managedObject': {
'distName': 'ethLink_1',
'operation': 'create_mo',
'parameter': [
{
'parameterName': 'houseName',
'newValue': 'Bhawan',
'prevValue': ''
},
{
'parameterName': 'subscribe',
'newValue': 'TRUE',
'prevValue': ''
},
{
'parameterName': 'remoteMacAddress',
'newValue': 'd6-68-05-5e-06-b9',
'prevValue': ''
}
],
'class': 'EthernetLink'
}
})]
)
dictionary_2 = dict([('modifyParameterReq', {
'managedObject': {
'distName': 'ethLink_1',
'operation': 'create_mo',
'parameter': [
{
'parameterName': 'subscribe',
'newValue': 'FALSE',
'prevValue': ''
},
{
'parameterName': 'remoteMacAddress',
'newValue': 'a1-b1-c3-d4-e5-f6',
'prevValue': ''
},
{
'parameterName': 'yourName',
'newValue': 'Vicky',
'prevValue': ''
}
],
'class': 'EthernetLink'
}
})
]
)
如果不存在该元素,则添加该元素,否则用新值替换。 任何帮助都应感谢。
答案 0 :(得分:0)
这应该做到。我在两者之间写了一些评论,以使其更具可读性:
# Get all current parameter names from dictionary 1.
currentDictParameterNames = [elem['parameterName'] for elem in dictionary_1['modifyParameterReq']['managedObject']['parameter']]
# Iterate through parameters from dictionary 2.
for index, dictData in enumerate(dictionary_2['modifyParameterReq']['managedObject']['parameter']):
# If current key iterated from dictionary 2 exists in dictionary 1, update.
if dictData['parameterName'] in currentDictParameterNames:
# FInd the location of the parameter name in dictionary 1 and update.
for i in range(len(dictionary_1['modifyParameterReq']['managedObject']['parameter'])):
if dictionary_1['modifyParameterReq']['managedObject']['parameter'][i]['parameterName'] == dictData['parameterName']:
dictionary_1['modifyParameterReq']['managedObject']['parameter'][i]['prevValue'] = dictionary_1['modifyParameterReq']['managedObject']['parameter'][i]['newValue']
dictionary_1['modifyParameterReq']['managedObject']['parameter'][i]['newValue'] = dictData['newValue']
break
# Else create a new record.
else:
dictionary_1['modifyParameterReq']['managedObject']['parameter'].append(dictData)
print(dictionary_1)
结果应为:
{'modifyParameterReq': {'managedObject': {
'distName': 'ethLink_1',
'operation': 'create_mo',
'parameter': [
{'parameterName': 'houseName', 'newValue': 'Bhawan', 'prevValue': ''},
{'parameterName': 'subscribe', 'newValue': 'FALSE', 'prevValue': 'TRUE'},
{'parameterName': 'remoteMacAddress', 'newValue': 'a1-b1-c3-d4-e5-f6', 'prevValue': 'd6-68-05-5e-06-b9'},
{'parameterName': 'yourName', 'newValue': 'Vicky', 'prevValue': ''}],
'class': 'EthernetLink',
}}}