如何订购字典python(排序)

时间:2022-11-17 07:40:07

I use Python dictionary:

我使用Python字典:

>>> a = {}
>>> a["w"] = {}
>>> a["a"] = {}
>>> a["s"] = {}
>>> a
{'a': {}, 's': {}, 'w': {}}

I need:

我需要:

>>> a
{'w': {}, 'a': {}, 's': {}}

How can I get the order in which I filled the dictionary?

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

2 个解决方案

#1


17  

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

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

An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

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

>>> import collections
>>> a = collections.OrderedDict()
>>> a['w'] = {}
>>> a['a'] = {}
>>> a['s'] = {}
>>> a
OrderedDict([('w', {}), ('a', {}), ('s', {})])
>>> dict(a)
{'a': {}, 's': {}, 'w': {}}

#2


3  

you should use OrderedDict instead of Dict.

你应该使用OrderedDict而不是Dict。

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

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

#1


17  

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

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

An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

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

>>> import collections
>>> a = collections.OrderedDict()
>>> a['w'] = {}
>>> a['a'] = {}
>>> a['s'] = {}
>>> a
OrderedDict([('w', {}), ('a', {}), ('s', {})])
>>> dict(a)
{'a': {}, 's': {}, 'w': {}}

#2


3  

you should use OrderedDict instead of Dict.

你应该使用OrderedDict而不是Dict。

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

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