16

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).

Duoran
  • 307
  • 1
  • 3
  • 7

2 Answers2

17

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 CPython 3.6, dict respects insertion order. Beginning with Python 3.7, it has become a documented guarantee.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
3

Yes, they are sorted in the same order as the keys are. This is the same with all dict implementations.

Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). Another way to create the same list is pairs = [(v, k) for (k, v) in d.items()].

https://docs.python.org/3/library/stdtypes.html#dict-views

lyschoening
  • 18,170
  • 11
  • 44
  • 54