Python - collections.OrderedDict() 未正确排序字典

标签 python string sorting dictionary ordereddictionary

我有一个字典列表如下:

[{'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)])  

再说一遍,这是没有订购的。如何使字典排序?

最佳答案

有两点需要注意:

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

考虑到这些方面,您可以使用 sorted 和定义的自定义 key 来构造元组列表。然后将此有序集合提供给 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 的附加方法,则可以将 OrderedDict 替换为 dict

关于Python - collections.OrderedDict() 未正确排序字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469708/

相关文章:

Python 套接字在远程使用所有数据之前关闭

google-app-engine - GAE 搜索 API 排序

python - 删除字符串中的重复 block

algorithm - 你能在 O(n/p) 时间内进行并行计数排序吗?

javascript - 使用 jquery sort() 函数对元素进行排序在 webkit 上失败

Python 将 Excel 转换为 CSV

python - 如何创建地理引用随机数据?

Python线性回归,残差的最佳拟合线

c# - 如何输出字符串中的所有其他单词?

string - 如何从字符串中删除变音符号(重音符号)?