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).
You'll have to create a new one since OrderedDict is sorted by insertion order.
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.
For example, dict does not allow duplicate keys.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With