__eq__ on a dict

Aaron Bingham bingham at cenix-bioscience.com
Tue Jul 12 03:19:03 EDT 2005


Hi Steven,

Thanks for digging into this.

"Steven D'Aprano" <steve at REMOVETHIScyber.com.au> writes:

> Replying to myself... how sad.
>
> On Tue, 12 Jul 2005 15:41:46 +1000, Steven D'Aprano wrote:
>
>> 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.
>
> On reading it, that came across more snarky than I intended. Sorry.

It's ok.  I realize the OP did not make it crystal clear what he was
getting at in his post.  It's easier when you are sitting in the same
office ;-).

> However, I wasn't completely insane, since I came across this tidbit:
>
> http://python.active-venture.com/ref/comparisons.html
>
> "Mappings (dictionaries) compare equal if and only if their sorted (key,
> value) lists compare equal. Outcomes other than equality are resolved
> consistently, but are not otherwise defined."
>
> with a footnote leading to this comment:
>
> "Earlier versions of Python used lexicographic comparison of the sorted
> (key, value) lists, but this was very expensive for the common case of
> comparing for equality."

Ah, I missed that, thanks for the pointer.  Seems information of
dictionary comparisons should also appear in the Library Reference
under Mapping Types.

> I also suggested:
>
>> My second thought was that comparison is implemented by first comparing
>> keys, then values, ie cmp(dictA, dictB)
> [snip]
>> I don't think I can prove it though.

Looking at the source code links Simon posted (thanks Simon!) it is
clear that, in the current version of CPython, dictionaries are
ordered first by length and only if the lengths are equal are the
keys and values examined.

> Equality of dicts is guaranteed. Two dicts are equal if and only if their
> keys:value pairs are equal. Other orderings between dicts are calculated
> consistently but not in any documented way.
>
> One gotcha is that some dicts are unordered:
>
> py> {1:1j} < {1:2j}
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: cannot compare complex numbers using <, <=, >, >=
>
> but even that is special-cased up to the wazzoo:
>
> py> {1:1j} < {1:1j}
> False

Hmm... not sure I like that!

-- 
--------------------------------------------------------------------
Aaron Bingham
Senior Software Engineer
Cenix BioScience GmbH
--------------------------------------------------------------------




More information about the Python-list mailing list