OrderedDict: are values ordered, too?

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


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.

Tags:

Python