【问题标题】:how to order dictionary python (sorting)如何订购字典python(排序)
【发布时间】:2013-06-10 21:23:33
【问题描述】:

我使用 Python 字典:

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

我需要:

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

我怎样才能得到我填写字典的顺序?

【问题讨论】:

标签: python sorting dictionary


【解决方案1】:

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': {}}

【讨论】:

    【解决方案2】:

    您应该使用OrderedDict 而不是Dict

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

    【讨论】:

      猜你喜欢
      • 2011-11-07
      • 2010-10-26
      • 2012-05-10
      • 2021-11-02
      • 2011-05-15
      • 2023-01-30
      • 2012-09-21
      • 1970-01-01
      • 2022-11-13
      相关资源
      最近更新 更多