简体   繁体   中英

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

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.

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']

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])])
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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