如何订购字典python(排序) [英] how to order dictionary python (sorting)
本文介绍了如何订购字典python(排序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Python字典:
I use Python dictionary:
>>> a = {}
>>> a["w"] = {}
>>> a["a"] = {}
>>> a["s"] = {}
>>> a
{'a': {}, 's': {}, 'w': {}}
我需要:
>>> a
{'w': {}, 'a': {}, 's': {}}
如何获取填写字典的顺序?
How can I get the order in which I filled the dictionary?
推荐答案
http://docs.python.org/2/library/collections.html#collections.OrderedDict
一个OrderedDict是一个记录键首先被
插入的顺序的dict。如果新条目覆盖现有条目,则原始
插入位置保持不变。删除一个条目并重新插入
将会将其移动到最后。
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.
>>> import collections
>>> a = collections.OrderedDict()
>>> a['w'] = {}
>>> a['a'] = {}
>>> a['s'] = {}
>>> a
OrderedDict([('w', {}), ('a', {}), ('s', {})])
>>> dict(a)
{'a': {}, 's': {}, 'w': {}}
这篇关于如何订购字典python(排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文