Python:找出dicts的不同之处

eal*_*eon 2 python dictionary

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
Run Code Online (Sandbox Code Playgroud)

如果dictA和dictB中的项目数量巨大,则效率低下

有没有更快的方法呢?

我在想某种方式使用套装但不确定.

-

这可能是重复的,但似乎人们在其他类似问题的答案中迭代

Pad*_*ham 5

您可以使用dict view objetcs:

键视图设置类似,因为它们的条目是唯一且可清除的.如果所有值都是可清除的,那么(键,值)对是唯一且可清除的,那么items视图也是类似于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)])
Run Code Online (Sandbox Code Playgroud)

或者设置:

print(set(dictA.iteritems()).difference(dictB.iteritems()))
Run Code Online (Sandbox Code Playgroud)

你唯一的限制就是记忆