如何订购字典python(排序)

Olg*_*lga 3 python sorting dictionary

我使用Python字典:

>>> a = {}
>>> a["w"] = {}
>>> a["a"] = {}
>>> a["s"] = {}
>>> a
{'a': {}, 's': {}, 'w': {}}
Run Code Online (Sandbox Code Playgroud)

我需要:

>>> a
{'w': {}, 'a': {}, 's': {}}
Run Code Online (Sandbox Code Playgroud)

如何获得填写字典的顺序?

fal*_*tru 17

http://docs.python.org/2/library/collections.html#collections.OrderedDict

OrderedDict是一个dict,它记住了第一次插入键的顺序.如果新条目覆盖现有条目,则原始插入位置保持不变.删除条目并重新插入它将使其移至最后.

>>> import collections
>>> a = collections.OrderedDict()
>>> a['w'] = {}
>>> a['a'] = {}
>>> a['s'] = {}
>>> a
OrderedDict([('w', {}), ('a', {}), ('s', {})])
>>> dict(a)
{'a': {}, 's': {}, 'w': {}}
Run Code Online (Sandbox Code Playgroud)