Is there a description of how __cmp__ works for dict objects in Python 2?

I tried to subclass dict , inheriting from UserDict.DictMixin , which supports non-hashed keys. Performance is not a concern. Unfortunately, Python implements some of the functions in DictMixin , trying to create a dict object from a subclass. I can implement them myself, but I am stuck on __cmp__ .

I cannot find a brief description of the logic used by the built-in __cmp__ for the dict class.

+18
python
Aug 14 '10 at 17:05
source share
3 answers

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: # No difference. return 0 bdiff = smallest_diff_key(B, A) if adiff != bdiff: return cmp(adiff, bdiff) return cmp(A[adiff], b[bdiff]) 

This is translated from implementation 2.6.3 in the dictobject.c file.

+26
Aug 14 '10 at 17:49
source share
— -

An alternative is to use ABC Mapping from the collections package. It is available in version 2.6 and higher. You just inherit the collections. Create and apply the __getitem__ , __contains__ and __iter__ . You get everything else for free.

+2
Aug 14 '10 at 17:48
source share



All Articles