简体   繁体   English

使用OrderedDict按项目长度订购python字典

[英]Order a python dictionary by length of item using OrderedDict

Im trying to use OrderedDict to make a dictionary where the item is a list of entries, and I want the ordering to be based on the length of the item list. 我试图使用OrderedDict制作一个字典,其中项目是一个条目列表,我希望排序基于项目列表的长度。

say for: 说:

d = {2:[1], 1:[1,2,3], 4:[1,2], 5:[1,2,3,4]}

I tried: 我试过了:

od = collections.OrderedDict(sorted(len(d.items())))

but I got a TypeError: 'int' object is not iterable 但是我得到了一个TypeError: 'int' object is not iterable

I found a workaround by iterating something like this: 我通过迭代这样的事情找到了一个解决方法:

for k in sorted(d, key=lambda k: len(d[k]), reverse=True): 

when needed, but I'd rather the dict be sorted beforehand. 在需要的时候,但我宁愿事先对dict进行排序。

You could sort d.items() according to the length of the values : 您可以根据值的长度对d.items()进行排序

In [268]: sorted(d.items(), key=lambda x: len(x[1]), reverse=True)
Out[268]: [(5, [1, 2, 3, 4]), (1, [1, 2, 3]), (4, [1, 2]), (2, [1])]

and pass that to collections.OrderedDict : 并将其传递给collections.OrderedDict

In [267]: collections.OrderedDict(sorted(d.items(), key=lambda x: len(x[1]), reverse=True))
Out[267]: OrderedDict([(5, [1, 2, 3, 4]), (1, [1, 2, 3]), (4, [1, 2]), (2, [1])])

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

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