简体   繁体   中英

Sort dictionary by multiple values

I have the dictionary {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}

I need to sort this dictionary first numerically, then within that, alphabetically. If 2 items have the same number key, they need to be sorted alphabetically.

The output of this should be Bob, Alex, Bill, Charles

I tried using lambda, list comprehension, etc but I can't seem to get them to sort correctly.

Using sorted with key function (order by value ( d[k] ) first, then key k ):

>>> d = {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}    
>>> sorted(d, key=lambda k: (d[k], k))
['Bob', 'Alex', 'Bill', 'Charles']

Sort on the dictionary's items (which are tuples) using sorted() . You can specify the sort key which will be by the dictionary's values, and then its keys:

>>> d = {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}
>>> sorted(d.items(), key=lambda x:(x[1],x[0]))
[('Bob', 3), ('Alex', 4), ('Bill', 4), ('Charles', 7)]
>>> [t[0] for t in sorted(d.items(), key=lambda x:(x[1],x[0]))]
['Bob', 'Alex', 'Bill', 'Charles']

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