Python 2.7-在比较字典时仅显示修改后的字典键/值 [英] Python 2.7 - Show only modified dictionary key/value while comparing dictionaries
本文介绍了Python 2.7-在比较字典时仅显示修改后的字典键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试使用此代码比较两个字典:
Trying to compare two dictionaries with this code:
def dict_compare(d1, d2):
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
added = d1_keys - d2_keys
removed = d2_keys - d1_keys
modified = {o: (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
same = set(o for o in intersect_keys if d1[o] == d2[o])
return added, removed, modified, same
one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}}
two = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "Blue", "0.0.0.0/0"]}}
added, removed, modified, same = dict_compare(one,two)
print added
print removed
print modified
print same
但是,它会错误地打印修改后的键/值.
However, it prints the modified key/values wrongly.
输出:
set([])
set([])
{'1iG5NDGVre': ({'118': ['test1', 'test2', 'test3', 'tcp', '22', 'Red', '0.0.0.0/0']}, {'118': ['test1', 'test2', 'test3', 'tcp', '22', 'Red', 'Blue', '0.0.0.0/0']})}
set([])
有什么办法纠正它吗?
我只希望它在修改后显示蓝色".
I just want that it prints "Blue" in modified.
更新1:
有效,但当字典具有不同的键号时无效,即
Works but not when the dicts have different keys number i.e
one = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "0.0.0.0/0"]}}
two = {"1iG5NDGVre": {"118": ["test1", "test2", "test3", "tcp", "22", "Red", "Blue", "0.0.0.0/0"]},"119": ["test10","test11"]}
不会显示已添加的test10和test11.
Will not show up test10 and test11 as added.
字典也可以有更少的键,也可以删除键.还要涵盖这种情况.
Dict could also have less keys, key can be also removed. Want to also cover that case.
非常感谢!
推荐答案
您应该使用按位互斥或(^
)将列表与实际值进行比较:
You should compare the list with the actual values with a bitwise exclusive or (^
):
differences = set(one["1iG5NDGVre"]["118"]) ^ set(two["1iG5NDGVre"]["118"])
print differences
这篇关于Python 2.7-在比较字典时仅显示修改后的字典键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文