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中的项数很大,则效率低下
有更快的方法吗?
我在想以某种方式使用集合,但不确定。
-
这可能是重复的,但似乎人们在重复其他类似问题的答案
python大神给出的解决方案
您可以使用dict view objetcs:
键视图是类似集合的,因为它们的条目是唯一且可哈希的。如果所有值都是可哈希的,因此(键,值)对是唯一且可哈希的,则项目视图也将类似于集合。 (由于条目通常不是唯一的,因此值视图不会被视为类似集合的集合。)然后可以使用这些集合操作(“其他”是指另一个视图或集合):
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()))
您唯一的限制显然是记忆力