I'm reading @Martijn Pieters' response to Converting dict to OrderedDict. The main point of his answer is that passing a regular dict to OrderedDict()
will not retain the order as desired, because the dict that you are passing has already "lost" any semblance of order. His solution is to pass tuples that make up the dict's key/value pairs instead.
However, I also noticed the following in the docs:
Changed in version 3.6: With the acceptance of PEP 468, order is retained for keyword arguments passed to the OrderedDict
Does this invalidate the issue that Martijn points out (can you now pass a dict to OrderedDict), or am I misinterpreting?
from collections import OrderedDict
ship = {'NAME': 'Albatross',
'HP':50,
'BLASTERS':13,
'THRUSTERS':18,
'PRICE':250}
print(ship) # order lost as expected
{'BLASTERS': 13, 'HP': 50, 'NAME': 'Albatross', 'PRICE': 250, 'THRUSTERS': 18}
print(OrderedDict(ship)) # order preserved even though a dict is passed?
OrderedDict([('NAME', 'Albatross'),
('HP', 50),
('BLASTERS', 13),
('THRUSTERS', 18),
('PRICE', 250)])
I get this same (correct) order if I run a for key in ...
loop over the OrderedDict as well, seeming to imply it's OK to pass the dict itself.
Edit: this was also contributing a bit to my confusion: Are dictionaries ordered in Python 3.6+?