Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 719
Alexandre Avatar asked Dec 16 '15 12:12

Alexandre


People also ask

How do you define OrderedDict?

OrderedDict preserves the order in which the keys are inserted. A regular dict doesn't track the insertion order and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.

What is the difference between dict and OrderedDict?

The OrderedDict is a subclass of dict object in Python. The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.

How does OrderedDict work in Python?

Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.

Is OrderedDict sorted?

The OrderedDict() is a method of the Collections module that returns an instance of a dict subclass with a method specialized for rearranging dictionary order. The sorted() function returns a sorted list of the specified iterable object. The OrderedDict() method preserves the order in which the keys are inserted.


1 Answers

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.

like image 100
bruno desthuilliers Avatar answered Sep 23 '22 03:09

bruno desthuilliers