我想提取两个嵌套字典之间的差异,并希望结果包含完整的字典键路径。我已经安装了Python2.7和DeepDiff,这似乎是我想要实现的最佳选择。我正在尝试确定如何更改DeepDiff的输出,以便它提供完整的字典路径和值,而不是我无法索引的集。有没有更好的方法来改变输出(而不是将输出转换回字典)?你知道吗
代码:
from __future__ import print_function
from deepdiff import DeepDiff
knownAPs = {'WLC1': {'10.1.1.1': {'72.6': ['AP22', 'city'], '55.1': ['AP102', 'office']}}, 'WLC2': {'10.1.1.2': {}}}
discoveredAPs = {'WLC1': {'10.1.1.1': {}}, 'WLC2': {'10.1.1.2': {}}}
ddiff = DeepDiff(knownAPs, discoveredAPs)
if 'dic_item_added' in ddiff.keys():
print('Item added to known: ' + str((ddiff['dic_item_added'])))
if 'dic_item_removed' in ddiff.keys():
DisAssociatedAPs = (list(list(ddiff['dic_item_removed'])))
for i in DisAssociatedAPs:
fullkeypath = (str(i).strip('root'))
ControllerName = (fullkeypath[0])
ControllerIP = (fullkeypath[1])
AccessPointIndex = (fullkeypath[2])
print('AP: ' + str(knownAPs + fullkeypath) + ' on controller: ' + str(ControllerName) + ' was removed from the known database')
if 'values_changed' in ddiff.keys():
print('Item changed: ' + str((ddiff['values_changed'])))
输出
Traceback (most recent call last):
File "C:/xxx/testdic4.py", line 15, in <module>
print('AP: ' + str(knownAPs + fullkeypath) + ' on controller: ' + str(ControllerName) + ' was removed from the known database')
TypeError: unsupported operand type(s) for +: 'dict' and 'str'
Process finished with exit code 1
首选输出
AP: ['AP22', 'city'] on controller: ['WLC1'] was removed from the known database
AP: ['AP102', 'office'] on controller: ['WLC1'] was removed from the known database
问题正是回溯告诉您的:您正在尝试向字符串添加字典,这当然不是您想要的。具体地说,当您将
knownAPs
(typedict
)添加到fullkeypath
(typestr
)时,会出现一个错误,因为dict
不知道如何将自身添加到str
。你知道吗但这并不能回答您更普遍的问题,即如何以您想要的方式输出差异。试试这个:
相关问题 更多 >
编程相关推荐