关键字会在Python 3中自动排序吗?

时间:2018-08-22 00:48:53

标签: python python-3.x python-2.7

我正在研究Python3 tutorial on keyword arguments,由于以下代码,无法重现输出:

def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch 

我得到的是一个排序的字典:

----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

因此,我尝试不调用Cheeseshop():

>>> kw = {'shopkeeper':"Michael Palin", 'client':"John Cleese", 'sketch':"Cheese Shop Sketch"}
>>> kw
{'client': 'John Cleese', 'shopkeeper': 'Michael Palin', 'sketch': 'Cheese Shop Sketch'}

在3.5版中,键会自动排序。但是在2.7版中,它们不是:

>>> kw
{'shopkeeper': 'Michael Palin', 'sketch': 'Cheese Shop Sketch', 'client': 'John Cleese'}

我必须在2.7中对其进行排序,以同意3.5。

>>> for k in sorted(kw):
...     print(k + " : " + kw[k])
... 
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

因此,本教程中的语句:“请注意,关键字参数的打印顺序保证与在函数调用中提供它们的顺序匹配。”应该仅适用于2.7版,而不适用于3.5版。这是真的吗?

1 个答案:

答案 0 :(得分:0)

根据@Ry和@abamert的评论,我升级到Python 3.7,有关如何从<3.7>源代码构建它的步骤,请参见link1 link2link3。需要注意的是,Ubuntu 16.04的Python默认值为/ usr / bin中的2.7和3.5版本。升级后,3.7驻留在/ usr / local / bin中。因此,我们可以使三个版本共存。

正如他们所说,不要依赖特定版本的键顺序,因为版本2.7、3.5和3.7的行为彼此不同:

  1. <2.7>顺序是随机的,但一致/可重复。
  2. <3.5>顺序是随机且不一致的。
  3. <3.7>订单按输入保留,因此保持一致。
  4. 如果要对其进行排序,请使用OrderedDict。参见下文。

例如:

Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] 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
>>>