简体   繁体   English

Python:基于值对python字典进行排序的最佳方法; 值是列表

[英]Python : Best way to sort a python dictionary based on values ; values are lists

I have a python dictionary 我有一个python字典

d = {
    "Random" : [1,2,3], "Stupid" :  [1], "Gross" : [1,1,1,1,1], "Ugly" : [2,1,1,1]
    }

The above list should be sorted based on the count of the list values. 上面的列表应基于列表值的count进行排序。

I tried this : sorted(d, key=d.get, reverse=True) 我试过这个: sorted(d, key=d.get, reverse=True)

But I don't seem to get the right result. 但是我似乎没有得到正确的结果。

Do you mean length ? 你是说length吗?

>>> sorted(d, key=lambda k: -len(d[k]))
['Gross', 'Ugly', 'Random', 'Stupid']
>>> sorted(d, key=lambda k: len(d[k]), reverse=True)
['Gross', 'Ugly', 'Random', 'Stupid']

Since you are starting from a dictionary presumably you need to end with one, rather than a list so: 由于您从一本字典开始,大概需要以一个字典而不是一个列表结尾,因此:

>>> import collections
>>> d = {
...     "Random" : [1,2,3], "Stupid" :  [1], "Gross" : [1,1,1,1,1], "Ugly" : [2,1,1,1]
...     }
>>> sd = collections.OrderedDict(sorted(d.items(), key=lambda t: -len(t[1])))
>>> sd
OrderedDict([('Gross', [1, 1, 1, 1, 1]), ('Ugly', [2, 1, 1, 1]), ('Random', [1, 2, 3]), ('Stupid', [1])])
>>> 

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

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