在Python中的列表中按字典排序键 [英] Sort keys in dictionary by value in a list in Python
问题描述
我已经看到这篇文章和这篇文章以及许多其他人,但还没有找到我的问题的答案,也不能弄清楚。
I have seen this post and this post as well as many others, but haven't quite found the answer to my question nor can I figure it out.
我有一个列表的字典。例如,它看起来像:
I have a dictionary of lists. For example it looks like:
Dict = {'a':[1,2,3,4], 'b':[9,8,7,6], 'c':[8,5,3,2]}
我想根据列表中的特定项目返回排序(降序/反向)的键列表。例如,我想根据每个列表中的第四个项目对a,b,c进行排序。
I want to return a list of the keys sorted (descending/reverse) based on a specific item in the lists. For example, I want to sort a,b,c based on the 4th item in each list.
这应该返回列表 sorted_keys = [按照值
[6,4,2]
排序的'b','a','c']
This should return the list sorted_keys = ['b','a','c']
which were sorted by values [6,4,2]
.
有意义吗?请帮助...谢谢!
Make sense? Please help...thanks!
推荐答案
提供键
lambda
是最简单的,排序方式:
Supply a key
function, a lambda
is easiest, and sort reversed:
sorted(Dict.keys(), key=lambda k: Dict[k][3], reverse=True)
关键功能告诉排序
要排序什么>
The key function tells sorted
what to sort by; the 4th item in the value for the given key.
演示:
>>> sorted(Dict.keys(), key=lambda k: Dict[k][3], reverse=True)
['b', 'a', 'c']
这篇关于在Python中的列表中按字典排序键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!