[英]Find the differences between nested dictionaries which contain lists
我想提取兩個嵌套字典之間的差異,並希望結果包括完整的字典鍵路徑。 我已經安裝了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
(類型dict
)添加到fullkeypath
(類型str
)時,會出現錯誤,因為dict
不知道如何將自身添加到str
。
但這並不能回答您關於如何以所需方式輸出差異的更一般的問題。 嘗試這個:
diffs = deepdiff.DeepDiff(knownAPs, discoveredAPs)
def get_value_from_string(d, s):
s = list(filter(None, (piece[2:-1] for piece in s.split(']'))))
for piece in s:
d = d[piece]
return d
if 'dic_item_removed' in diffs:
for item in diffs['dic_item_removed']:
item = item.strip('root')
base = item[2:item.find(']') - 1]
print('AP:', get_value_from_string(knownAPs, item),
'on controller: \'' + base + '\' was removed from the known '
'database')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.