Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderedDict: are values ordered, too? [duplicate]

Tags:

python

The collections.OrderedDict documentation describes an OrderedDict as a

a dict that remembers the order that keys were first inserted

so the order of

for k in dict:
  ...

for k in dict.keys():
  ...

is predictable.

However, it does not say anything about values. If I only need to iterate over the values as follows, will the results respect the ordering-by-insert as well?

for v in dict.values():
  ...

A few quick tests here in CPython showed that to be the case, but that could just be coinicidental with the current implementation (I haven't tested any others).

like image 882
Duoran Avatar asked Feb 27 '15 10:02

Duoran


People also ask

Is OrderedDict sorted?

You'll have to create a new one since OrderedDict is sorted by insertion order.

Is OrderedDict a doubly linked list?

Both implementations of OrderedDict involve using a doubly linked list to capture the order of items. Despite having linear time for some operations, the linked list implementation in OrderedDict is highly optimized to preserve the fast times of the corresponding dictionary methods.

Can ordered dict have duplicate keys?

For example, dict does not allow duplicate keys.

What is the difference between dict and OrderedDict?

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.


1 Answers

Yes, the lists by keys() and values() are arranged in corresponding orders in all dicts, not just in ordered ones.

Prior to Python 3.6, the order was arbitrary for normal dicts, but it was the same arbitrary order returned by keys(), values() and items(), provided the dict wasn't modified between calls to those methods.

As of Python 3.6, dict respects insertion order. Beginning with 3.7, it has become a documented guarantee.

like image 162
user4815162342 Avatar answered Sep 21 '22 18:09

user4815162342