Reputation: 5869
I have a python dictionary
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.
I tried this : sorted(d, key=d.get, reverse=True)
But I don't seem to get the right result.
Upvotes: 2
Views: 540
Reputation: 28405
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])])
>>>
Upvotes: 1
Reputation: 369304
Do you mean 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']
Upvotes: 4