If you ask how dictionary comparison works, here's what:
- To compare dicts A and B, first compare their lengths. If they are not equal, return cmp (len (A), len (B)).
- Then find the adiff key in A, which is the smallest key for which
adiff not in B or A[adiff] != B[adiff] . (If there is no such key, dicts are equal.) - Also find the smallest bdiff key in B for which
bdiff not in A or A[bdiff] != B[bdiff] . - If adiff! = Bdiff, return cmp (adiff, bdiff). Else return cmp (A [adiff], B [bdiff]).
In pseudo code:
def smallest_diff_key(A, B): """return the smallest key adiff in A such that adiff not in B or A[adiff] != B[bdiff]""" diff_keys = [k for k in A if k not in B or A[k] != B[k]] return min(diff_keys) def dict_cmp(A, B): if len(A) != len(B): return cmp(len(A), len(B)) try: adiff = smallest_diff_key(A, B) except ValueError:
This is translated from implementation 2.6.3 in the dictobject.c file.
Ned Batchelder Aug 14 '10 at 17:49 2010-08-14 17:49
source share