[英]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]}
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.
例如,我想根据每个列表中的第4项对a,b,c进行排序。
This should return the list sorted_keys = ['b','a','c']
which were sorted by values [6,4,2]
. 这应该返回列表
sorted_keys = ['b','a','c']
,它们按值[6,4,2]
排序。
Make sense? 说得通? Please help...thanks!
请帮忙......谢谢!
Supply a key
function, a lambda
is easiest, and sort reversed: 提供一个
key
功能, lambda
最简单,并且反转排序:
sorted(Dict.keys(), key=lambda k: Dict[k][3], reverse=True)
The key function tells sorted
what to sort by ; 关键功能告诉
sorted
要排序的内容 ; the 4th item in the value for the given key. 给定键值的第4项。
Demo: 演示:
>>> sorted(Dict.keys(), key=lambda k: Dict[k][3], reverse=True)
['b', 'a', 'c']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.