dictionary - Python: find difference in dicts -
dicta = {'a':1, 'b':2, 'c':3} dictb = {'a':2, 'b':2, 'c':4} if dicta == dictb: print "dicts same" else: # print diffs key in dicta.iterkeys(): try: if dicta[key] != dictb[key]: print "different value key: %s" % key except keyerror: print "dictb has no key: %s" % key
this gets inefficient if number of items in dicta , dictb huge
any faster way this?
i thinking somehow using sets not sure.
--
this might duplicate seems people iterating in answers in other similar questions
you can use dict view objetcs:
keys views set-like since entries unique , hashable. if values hashable, (key, value) pairs unique , hashable, items view set-like. (values views not treated set-like since entries not unique.) these set operations available (“other” refers either view or set):
dictview & other return intersection of dictview , other object new set. dictview | other return union of dictview , other object new set. dictview - other return difference between dictview , other object (all elements in dictview aren’t in other) new set. dictview ^ other return symmetric difference (all elements either in dictview or other, not in both) of dictview , other object 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 restriction have memory
Comments
Post a Comment