如何按值对 Python dict 的键进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3417760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a Python dict's keys by value
提问by Shane Reustle
I have a dict that looks like this
我有一个看起来像这样的字典
{ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }
{ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }
And I would like to convert it DESC and create a list of just the keywords. Eg, this would return
我想将其转换为 DESC 并创建一个仅包含关键字的列表。例如,这将返回
["keyword3" , "keyword1" , "keyword4" , "keyword2"]
["keyword3" , "keyword1" , "keyword4" , "keyword2"]
All examples I found use lambda and I'm not very strong with that. Is there a way I could loop through this, and sort them as I go? Thanks for any suggestions.
我发现的所有示例都使用 lambda,但我对此不是很了解。有没有办法可以循环遍历这个,并在我进行时对它们进行排序?感谢您的任何建议。
PS: I could create the initial dict differently if it would help.
PS:如果有帮助,我可以以不同的方式创建初始字典。
采纳答案by kennytm
You could use
你可以用
res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))
(You don't need the listin Python 2.x)
(您不需要listPython 2.x 中的 )
The theDict.__getitem__is actually equivalent to lambda x: theDict[x].
该theDict.__getitem__实际上相当于lambda x: theDict[x]。
(A lambda is just an anonymous function. For example
(一个 lambda 只是一个匿名函数。例如
>>> g = lambda x: x + 5
>>> g(123)
128
This is equivalent to
这相当于
>>> def h(x):
... return x + 5
>>> h(123)
128
)
)
回答by JiminyCricket
i always did it this way....are there advantages to using the sorted method?
我总是这样做....使用排序方法有好处吗?
keys = dict.keys()
keys.sort( lambda x,y: cmp(dict[x], dict[y]) )
whoops didnt read the part about not using lambda =(
哎呀没有阅读有关不使用 lambda 的部分 =(
回答by Messa
I would come up with something like this:
我会想出这样的东西:
[k for v, k in sorted(((v, k) for k, v in theDict.items()), reverse=True)]
But KennyTM's solutionis much nicer :)
但是KennyTM 的解决方案要好得多:)
回答by John La Rooy
>>> d={ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }
>>> sorted(d, key=d.get, reverse=True)
['keyword3', 'keyword1', 'keyword4', 'keyword2']
回答by Sagar Pise
It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently order less, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples. For instance,
无法对 dict 进行排序,只能获得已排序的 dict 的表示。字典本质上顺序较少,但其他类型,例如列表和元组,则不是。所以你需要一个排序的表示,这将是一个列表——可能是一个元组列表。例如,
'''
Sort the dictionary by score. if the score is same then sort them by name
{
'Rahul' : {score : 75}
'Suhas' : {score : 95}
'Vanita' : {score : 56}
'Dinesh' : {score : 78}
'Anil' : {score : 69}
'Anup' : {score : 95}
}
'''
import operator
x={'Rahul' : {'score' : 75},'Suhas' : {'score' : 95},'Vanita' : {'score' : 56},
'Dinesh' : {'score' : 78},'Anil' : {'score' : 69},'Anup' : {'score' : 95}
}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
print sorted_x
output:
输出:
[('Vanita', {'score': 56}), ('Anil', {'score': 69}), ('Rahul', {'score': 75}), ('Dinesh', {'score': 78}), ('Anup', {'score': 95}), ('Suhas', {'score': 95})]

