I'm trying to create an OrderedDict object but no sooner do I create it, than the elements are all jumbled.
This is what I do:
from collections import OrderedDict od = OrderedDict({(0,0):[2],(0,1):[1,9],(0,2):[1,5,9]})
The elements don't stay in the order I assign
od OrderedDict([((0, 1), [1, 9]), ((0, 0), [2]), ((0, 2), [1, 5, 9])])
docs.python.org doesn't have an example and I can't figure out why the order is getting jumbled. Any help is greatly appreciated.
Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.
Standard dict objects preserve order in the reference (CPython) implementations of Python 3.5 and 3.6, and this order-preserving property is becoming a language feature in Python 3.7.
OrderedDict is over 80% slower than the standard Python dictionary (8.6/4.7≈1.83).
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.
Your problem is that you are constructing a dict
to give the initial data to the OrderedDict
- this dict
doesn't store any order, so the order is lost before it gets to the OrderedDict
.
The solution is to build from an ordered data type - the easiest being a list
of tuple
s:
>>> from collections import OrderedDict >>> od = OrderedDict([((0, 0), [2]), ((0, 1), [1, 9]), ((0, 2), [1, 5, 9])]) >>> od OrderedDict([((0, 0), [2]), ((0, 1), [1, 9]), ((0, 2), [1, 5, 9])])
It's worth noting that this is why OrderedDict
uses the syntax it does for it's string representation - string representations should try to be valid Python code to reproduce the object where possible, and that's why the output uses a list of tuples instead of a dict.
Edit: As of Python 3.6, kwargs
is ordered, so you can use keyword arguments instead, provided you are on an up-to-date Python version.
As of 3.7, this is also true for dict
s (it was for CPython in 3.6, but the language spec didn't specify it, so using OrderedDict
was still required for compatibility). This means if you can assume a 3.7+ environment, you can often drop OrderedDict
altogether, or construct one from a regular dict
if you need a specific feature (e.g: order to matter for equality).
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