我最近从Python 2.7切换到Python 3.3,似乎在Python 2中字典键的排序是任意的但一致的,而在Python 3中,例如使用
如果我运行:
vars()
获取的字典键的顺序似乎是不确定的。如果我运行:
class Test(object): pass
parameters = vars(Test)
print(list(parameters.keys()))
如果在Python 2.7和Python 3.3中都需要,那么:
Python 2.7 consistently gives me
['__dict__', '__module__', '__weakref__', '__doc__']
With Python 3.3, I can get any random order – for example:
['__weakref__', '__module__', '__qualname__', '__doc__', '__dict__'] ['__doc__', '__dict__', '__qualname__', '__module__', '__weakref__'] ['__dict__', '__module__', '__qualname__', '__weakref__', '__doc__'] ['__weakref__', '__doc__', '__qualname__', '__dict__', '__module__']
list({str(i): i for i in range(10)}.keys())
始终保持一致,每次运行都提供相同的结果
['3', '2', '1', '0', '7', '6', '5', '4', '9', '8']
… ?
{str(i): i for i in range(10)}
这样的东西呢? - Anaphory