[PYTHON] OrderedDict constructor behavior

Recently, when I decided to use Ordered Dict for the first time in a long time, I was thinking, "I have to pay attention to the behavior of the constructor." When I googled, I saw many articles in Japanese like that, I read the docs just in case, and the behavior changed in 3.6.

Changed in version 3.6: With the acceptance of PEP 468, order is retained for keyword arguments passed to the OrderedDict constructor and its update() method.

Quote: python3.6 documentation

code

from collections import OrderedDict

od = OrderedDict(
    a=0,
    b=1,
    c=2
)
print(''.join(od))

Expected output is ʻabc`

Execution result

3.6.2

~/G/B/o/3.6 ❯❯❯ python od_constract.py
abc
~/G/B/o/3.6 ❯❯❯ python od_constract.py
abc
~/G/B/o/3.6 ❯❯❯ python od_constract.py
abc
~/G/B/o/3.6 ❯❯❯ python od_constract.py
abc
~/G/B/o/3.6 ❯❯❯ python od_constract.py
abc

Output in the order of ʻabc`

3.5.3

~/G/B/o/3.5 ❯❯❯ python od_constract.py
cab
~/G/B/o/3.5 ❯❯❯ python od_constract.py
bca
~/G/B/o/3.5 ❯❯❯ python od_constract.py
acb
~/G/B/o/3.5 ❯❯❯ python od_constract.py
abc
~/G/B/o/3.5 ❯❯❯ python od_constract.py
acb

A sequence other than ʻabc` is output

2.7.13

~/G/B/o/2.7 ❯❯❯ python od_constract.py
acb
~/G/B/o/2.7 ❯❯❯ python od_constract.py
acb
~/G/B/o/2.7 ❯❯❯ python od_constract.py
acb
~/G/B/o/2.7 ❯❯❯ python od_constract.py
acb
~/G/B/o/2.7 ❯❯❯ python od_constract.py
acb

For some reason, it is output in the order of ʻacb`

The OrderedDict constructor and update() method both accept keyword arguments, but their order is lost because Python’s function call semantics pass-in keyword arguments using a regular unordered dictionary.

Quote: python2.7 documentation

Summary

Use *** 3.6! ***

Recommended Posts

OrderedDict constructor behavior
FTP behavior