Sort dictionary by multiple values

China☆狼群 提交于 2020-02-19 08:33:31

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/34170515/sort-dictionary-by-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!