What's wrong with passing dict to OrderedDict?

I am reading @Martijn Pieters answer on Converting dict to OrderedDict . The main point of his answer is that passing a regular dict to OrderedDict()

will not preserve order at will, because the dict you are passing through has already "lost" any semblance of order. His solution is to pass in tuples that make up the dict key / key pairs.

However, I also noticed the following in the docs :

Changed in version 3.6: When PEP 468 was adopted, order retained for keyword arguments passed to OrderedDict

Does this invalidate the question that Martijn points out (can you now pass 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 loop for key in ...

over the OrderedDict, and it seems to imply that it should skip the dict itself.

Edit : This also helped confuse me a bit: Are dictionaries ordered in Python 3.6+?

+3


source to share


1 answer


Order is retained for keyword arguments passed to OrderedDict

This means that order is guaranteed:

od = OrderedDict(a=20, b=30, c=40, d=50)

      

that is, the order in which the keyword arguments are passed is preserved in **kwargs

. This, in Python 3.6, is a language feature; all other implementations should follow suit.

How it works is that in order for this call to be made, a dictionary is created containing the keyword arguments. In being dict

, before 3.6

, he lost information about the order in which they were delivered.



With the adoption of PEP 468 in 3.6, this ensures that the ordered collation that applies to this information will now be used (in CPython, "ordered collation" happens like dict

, but that's an implementation detail - Update: Language feature as of Python 3.7.).


Using the OrderedDict(ship)

way you are doing it now also preserves the order in 3.6

, because it dict

has this implementation now, not because of PEP 468. This is something you shouldn't depend on as it counts as a CPython implementation; this may change in the future (and it looks like it will), but until then you shouldn't depend on it.

As of Python 3.7, the previous one now guarantees that the order is preserved between implementations, since the dict

insertion order is now a language feature.

+7


source







All Articles