【问题标题】:Sort a dictionary [duplicate]对字典进行排序[重复]
【发布时间】:2025-12-29 08:45:07
【问题描述】:
sorted_event_types={}
        for key,value in sorted(event_types.items()):
            sorted_event_types[key]=value


(Pdb) print sorted_event_types
{'ch': 1, 'eh': 2, 'oh': 3, 'ah': 0, 'as': 1, 'cs': 0, 'os': 5, 'es': 9}
(Pdb) event_types
{'as': 1, 'ch': 1, 'eh': 2, 'oh': 3, 'cs': 0, 'ah': 0, 'os': 5, 'es': 9}

我想对字典进行排序并保持这种方式。

输出应该是{'ah': 1, 'as': 1, 'ch': 2, 'cs': 3, 'eh': 0, ...}

【问题讨论】:

  • 那么问题到底是什么?
  • OrderedDict(虽然我可能会把它变成一个列表,因为我喜欢分离)
  • 遗憾的是,重复的问题有 OrderedDict(无论是否合适)的答案,而被埋没了..
  • 恕我直言,重复的问题与 OP 的要求无关。我认为this one 更相关。

标签: python string python-2.7 dictionary


【解决方案1】:

字典没有任何顺序感,它们是键值对的无序集合。

如果你想维持秩序,你应该使用collections.OrderedDict。示例 -

import collections
sorted_event_types = collections.OrderedDict()
for key,value in sorted(event_types.items()):
    sorted_event_types[key]=value

【讨论】:

    【解决方案2】:

    字典是无序的集合。您可以使用已排序的数据创建collections.OrderedDict 以保持顺序:

    >>> import collections
    >>> sorted_event_types = collections.OrderedDict(sorted(event_types.items()))
    >>> print sorted_event_types
    OrderedDict([('ah', 0), ('as', 1), ('ch', 1), ('cs', 0), ('eh', 2), ('es', 9), ('oh', 3), ('os', 5)])
    

    【讨论】: