首页 > 解决方案 > Python - collections.OrderedDict() 没有正确排序字典

问题描述

我有一个字典列表如下:

[{'17': 1}, {'17': 1, '19': 1}, {'8': 1, '9': 2, '12': 3}, {'23': 3}]

我想通过以下方式合并列表中的字典:

    from collections import Counter

    c = Counter()
    for d in hourofDayData:
        c.update(d)
    temp = dict(c)  

我得到以下输出:

{'17': 2, '19': 1, '8': 1, '9': 2, '12': 3, '23': 3}  

这就是我想要的,只是没有订购。我希望上面的字典像:

{'8': 1, '9': 2, '12': 3,'17': 2, '19': 1,  '23': 3}  

我尝试像这样使用 collections.OrderedDict:

OrderedDict([('12', 3), ('17', 2), ('19', 1), ('23', 3), ('8', 1), ('9', 2)])  

再次,没有订购。如何使字典排序?

标签: pythonstringsortingdictionaryordereddictionary

解决方案


需要注意的两点:

  1. OrderedDict是按插入排序的,而不是按大小排序的。
  2. 你的键是字符串。要按整数大小排序,您需要将它们转换为整数。

考虑到这些方面,您可以使用sortedkey定义定义来构造元组列表。然后将此有序集合提供给OrderedDict

d = {'17': 2, '19': 1, '8': 1, '9': 2, '12': 3, '23': 3}

from collections import OrderedDict

res = OrderedDict(sorted(d.items(), key=lambda x: int(x[0])))

结果:

OrderedDict([('8', 1), ('9', 2), ('12', 3), ('17', 2), ('19', 1), ('23', 3)])

值得注意的是,Python 3.7 中的字典是按插入顺序排列的,这个事实是可以信赖的。在这种情况下,OrderedDict可以替换为不需要dict的附加方法。OrderedDict


推荐阅读