按多个值对字典排序 [英] Sort dictionary by multiple values

查看:84
本文介绍了按多个值对字典排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字典{'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}

我需要首先对这本词典进行数字排序,然后在其中对其进行字母排序.如果2个项目具有相同的数字键,则需要按字母顺序对其进行排序.

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.

此输出应为Bob, Alex, Bill, Charles

我尝试使用lambda,列表理解等,但似乎无法正确排序.

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

推荐答案

使用 sorted 具有键功能(首先按值(d[k])排序,然后再按k键):

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

这篇关于按多个值对字典排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆