dict order

Peter Otten __peter__ at web.de
Wed Jun 18 08:08:10 EDT 2008


Robert Bossy wrote:

> I wish to know how two dict objects are compared. By browsing the
> archives I gathered that the number of items are first compared, but if
> the two dict objects have the same number of items, then the comparison
> algorithm was not mentioned.

If I interpret the comments in 

http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=64048&view=markup

correctly it's roughly

def characterize(d, e):
    return min(((k, v) for k, v in d.iteritems() if k not in e or e[k] != v),
               key=lambda (k, v): k)

def dict_compare(d, e):
    result = cmp(len(d), len(e))
    if result:
        return result
    try:
        ka, va = characterize(d, e)
    except ValueError:
        return 0
    kb, vb = characterize(e, d)
    return cmp(ka, kb) or cmp(va, vb)

Peter



More information about the Python-list mailing list