Skip to content Skip to sidebar Skip to footer

Are Keywords Automatically Sorted In Python 3?

I am studying Python3 tutorial on keyword arguments and couldn't reproduce the output due to the following code: def cheeseshop(kind, *arguments, **keywords): print('-- Do you

Solution 1:

Following the comments from @Ry and @abamert, I upgraded to Python 3.7, see link1link2 and link3 for steps on how to build it from <3.7> source code. One note is that the Python default for Ubuntu 16.04 are versions 2.7 and 3.5 in /usr/bin. After the upgrade, 3.7 resides in /usr/local/bin. So we can have three versions coexistent.

As they said, do not rely on a particular version for the key order since the behavior of versions 2.7, 3.5 and 3.7 is different from each other:

  1. <2.7> order is random, but consistent/repeatable.
  2. <3.5> order is random and inconsistent.
  3. <3.7> order is preserved as entered and thus consistent.
  4. Use OrderedDict if you want it to be sorted. see below.

For example:

Python 3.5.2 (default, Nov 232017, 16:37:01)
[GCC 5.4.020160609] on linux
Type"help", "copyright", "credits"or"license"for more information.
>>> kw = {'shopkeeper':"Michael Palin", 'client':"John Cleese", 'sketch':"Cheese Shop Sketch"}
>>> kw
{'client': 'John Cleese', 'shopkeeper': 'Michael Palin', 'sketch': 'Cheese Shop Sketch'}
>>>
>>> from collections import OrderedDict
>>> kws = OrderedDict(sorted(kw.items(), key = lambda x:x[0]))
>>> kws
OrderedDict([('client', 'John Cleese'), ('shopkeeper', 'Michael Palin'), ('sketch', 'Cheese Shop Sketch')])
>>> for i in kws:
... print(i + " :\t" + kws[i])
...
client :        John Cleese
shopkeeper :    Michael Palin
sketch :        Cheese Shop Sketch
>>>

Post a Comment for "Are Keywords Automatically Sorted In Python 3?"