ealeon
ealeon

Reputation: 12452

Python: find difference in dicts

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

This gets inefficient if the number of items in dictA and dictB are huge

Any faster way to do this?

I was thinking somehow using sets but not sure.

--

this might be a duplicate but it seems people are iterating in answers in other similar questions

Upvotes: 2

Views: 128

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can use 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)])

Or sets:

print(set(dictA.iteritems()).difference(dictB.iteritems()))

The only restriction you have is obviously memory

Upvotes: 5

Related Questions