python - 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)])
再次,没有订购。如何使字典排序?
解决方案
需要注意的两点:
OrderedDict
是按插入排序的,而不是按大小排序的。- 你的键是字符串。要按整数大小排序,您需要将它们转换为整数。
考虑到这些方面,您可以使用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
可以替换为不需要dict
的附加方法。OrderedDict
推荐阅读
- tensorflow - 如何将任何 Keras 层作为单个层运行以了解其行为?
- python - 使用 Python 3 和 __pycache__
- node.js - 如何在 http 模块中收听没有“/”的路径
- c# - 为什么 C# 不允许泛型类型用作泛型类中的属性?
- android - 使用 ByteArrayOutputStream 获取带有流式 GSON 的 JSON 字符串获取 OutOfMemoryError
- google-cloud-platform - 建议 Datalake / 数据仓库 BigQuery 设置
- azure - 如何将 Azure 混合权益应用于托管实例?
- javascript - Web开发中字符串的旋转替换效果
- deployment - 在 kubernetes StatefulSet 中按顺序创建 Pod
- angular - ASP.NET Core - 仅将一个区域作为 ANGULAR SPA 应用程序