dict order
Robert Bossy
Robert.Bossy at jouy.inra.fr
Wed Jun 18 08:35:28 EDT 2008
Peter Otten wrote:
> 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)
Thanks, Peter! That was exactly what I was looking for. Quite clever, I
might add.
RB
More information about the Python-list
mailing list