__eq__ on a dict

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Jul 12 07:41:46 CEST 2005

On Mon, 11 Jul 2005 13:54:05 +0200, Aaron Bingham wrote:

>> Two dicts are equal if they have the same keys and the same values.
> That is what I would expect, but where is that documented?  Also,
> where is the behavior of the much less obvious dictionary methods
> __ge__, __gt__, __le__, __lt__, and __cmp__ methods documented?
>> In general, you should not call __eq__ directly, but use the == operator
>> instead.
> That is clear enough, the OP was seeking information about the
> behavior of these operators when used with dictionaries.

That wasn't clear from his post at all. If he had explained what he
wanted, I wouldn't have wasted my time explaining what he already knew.

You know, something like "I already know that __eq__ is equivalent to ==,
likewise for the other operators > etc, what I want to know is how are
equality, less than, greater than, etc implemented specifically for dicts."

Asking the right question helps. But not in this case, because comparison
of objects is ... confusing. There doesn't seem to be any definitive
answer to the question, not that I have been able to find, although plenty
of hints.

My first thought was the comparisons between dicts is implemented as
comparisons between their items, ie cmp(dictA, dictB) is turned into
cmp(dictA.items(), dictB.items()). But that doesn't seem to be the case:

py> dictA = {None: None, 1:1}
py> dictB = {1: 1}
py> cmp(dictA, dictB)
py> cmp(dictA.items(), dictB.items())

My second thought was that comparison is implemented by first comparing
keys, then values, ie cmp(dictA, dictB) turns into:

order = cmp(dictA.keys(), dictB.keys()) 
if order == 0: # keys are equal
    order = cmp(dictA.values(), dictB.values())
return order

I don't think I can prove it though.


More information about the Python-list mailing list