Search code examples
pythonpython-3.xdictionaryordereddictionary

Why are the values of an OrderedDict not equal?


With Python 3:

>>> from collections import OrderedDict
>>> d1 = OrderedDict([('foo', 'bar')])
>>> d2 = OrderedDict([('foo', 'bar')])

I wanted to check for equality:

>>> d1 == d2
True
>>> d1.keys() == d2.keys()
True

But:

>>> d1.values() == d2.values()
False

Do you know why values are not equal?

I've tested this with Python 3.4 and 3.5.


Following this question, I posted on the Python-Ideas mailing list to have additional details:

https://mail.python.org/pipermail/python-ideas/2015-December/037472.html


Solution

  • In Python 3, dict.keys() and dict.values() return special iterable classes - respectively a collections.abc.KeysView and a collections.abc.ValuesView. The first one inherit it's __eq__ method from set, the second uses the default object.__eq__ which tests on object identity.