简体   繁体   English

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

[英]Python - collections.OrderedDict() is not ordering dictionary properly

I have a list of dictionary as follows:我有一个字典列表如下:

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

I want to merge the dictionaries in the list which I do by:我想通过以下方式合并列表中的字典:

    from collections import Counter

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

for which I get the following output:我得到以下输出:

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

which is what I want, except that it is not ordered.这就是我想要的,只是它没有被订购。 I want the above dictionary to be like:我希望上面的字典是这样的:

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

I tried to use collections.OrderedDict like this:我尝试像这样使用 collections.OrderedDict:

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

Again, which is not ordered.同样,这不是有序的。 How do I make the dictionary ordered?如何使字典有序?

Two points to note:需要注意的两点:

  1. OrderedDict is insertion ordered, not ordered by size. OrderedDict是插入排序,而不是按大小排序。
  2. Your keys are strings.你的钥匙是字符串。 For ordering by integer size, you need to convert them to integers.要按整数大小排序,您需要将它们转换为整数。

Considering these aspects, you can use sorted with a custom key defined to construct a list of tuples.考虑到这些方面,您可以使用sorted定义的自定义key来构造元组列表。 Then feed this ordered collection to OrderedDict :然后将此有序集合提供给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])))

Result:结果:

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

It is worth noting in Python 3.7 dictionaries are insertion ordered and this fact can be relied upon.值得注意的是,Python 3.7 中的字典是按插入顺序排列的,这一事实是可以信赖的。 In this case, OrderedDict can be replaced by dict provided the additional methods of OrderedDict are not required.在这种情况下, OrderedDict可以替换为dict前提是不需要OrderedDict的其他方法。

You should sort the dictionary first then you should convert it to ordereddict.您应该先对字典进行排序,然后再将其转换为ordereddict。 Check the following code.检查以下代码。

import collections
from collections import Counter

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

c = Counter()
for d in hourofDayData:
    c.update(d)
temp = dict(c)
def get_key(key):
    try:
        return int(key)
    except ValueError:
        return key
print(collections.OrderedDict(sorted(temp.items(), key=lambda t: get_key(t[0]))))

Prints:印刷:

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

Given:鉴于:

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

You can do:你可以做:

from collections import OrderedDict

cnt={}
for d in times:
    for k, v in d.items():
        cnt[k]=cnt.get(k, 0)+v

>>> OrderedDict(sorted([(k,v) for k,v in cnt.items()], key=lambda t:int(t[0])))
OrderedDict([('8', 1), ('9', 2), ('12', 3), ('17', 2), ('19', 1), ('23', 3)])

With Python 3.6+, you do not need to use OrderedDict since the keys of a regular dict use insertion order.使用 Python 3.6+,您不需要使用OrderedDict因为常规dict的键使用插入顺序。

Python 3.7:蟒蛇 3.7:

cnt={}
for d in times:
    for k, v in d.items():
        cnt[k]=cnt.get(k, 0)+v

>>> dict(sorted([(k,v) for k,v in cnt.items()], key=lambda t:int(t[0])))  
{'8': 1, '9': 2, '12': 3, '17': 2, '19': 1, '23': 3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM