dictA = {'a':1, 'b':2, 'c':3}
dictB = {'a':2, 'b':2, 'c':4}
if dictA == dictB:
print "dicts are same"
else:
# print all the diffs
for key in dictA.iterkeys():
try:
if dictA[key] != dictB[key]:
print "different value for key: %s" % key
except KeyError:
print "dictB has no key: %s" % key
如果 dictA 和 dictB 中的项目数量很大,这会变得低效
还有更快的方法吗?
我正在考虑以某种方式使用集合,但不确定。
--
这可能是重复的,但人们似乎正在迭代其他类似问题的答案
最佳答案
您可以使用dict view objetcs :
Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) Then these set operations are available (“other” refers either to another view or a set):
dictview & other
Return the intersection of the dictview and the other object as a new set.
dictview | other
Return the union of the dictview and the other object as a new set.
dictview - other
Return the difference between the dictview and the other object (all elements in dictview that aren’t in other) as a new set.
dictview ^ other
Return the symmetric difference (all elements either in dictview or other, but not in both) of the dictview and the other object as a new set.
diff = dictA.viewkeys() - dictB.viewkeys()
print(diff)
set([])
print(dictA.viewitems() - dictB.viewitems())
set([('a', 1), ('c', 3)])
或设置:
print(set(dictA.iteritems()).difference(dictB.iteritems()))
你唯一的限制显然是内存
关于Python:查找字典中的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761207/