DEV Community

Discussion on: 3 Common Mistakes that Python Newbies Make

Collapse
 
idanarye profile image
Idan Arye

dict ordering is important because keyword arguments are stored in a dict. Consider this:

$ python3.4
Python 3.4.8 (default, Jun 23 2018, 02:35:33) 
[GCC 8.1.1 20180531] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>> OrderedDict(a=1, b=2, c=3)
OrderedDict([('a', 1), ('c', 3), ('b', 2)])
>>> OrderedDict(c=1, b=2, a=3)
OrderedDict([('a', 3), ('c', 1), ('b', 2)])

We created an OrderedDict, but the constructor was using **kwargs which means the arguments we passed to it were stored in a regular dict and got reordered before OrderedDict.__init__ could store them in order.

With Python 3.6+, the **kwargs stores the arguments in the same order they were written, and the OrderedDict construction works as expected:

$ python3.6
Python 3.6.6 (default, Jun 27 2018, 13:11:40) 
[GCC 8.1.1 20180531] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>> OrderedDict(a=1, b=2, c=3)
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> OrderedDict(c=1, b=2, a=3)
OrderedDict([('c', 1), ('b', 2), ('a', 3)])