如何按值对Python字典排序? [英] How to sort a Python dictionary by value?
本文介绍了如何按值对Python字典排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Possible Duplicate:
In Python how do I sort a list of dictionaries by values of the dictionary?
Sorting Python dictionary based on nested dictionary values
我有以下形式的字典:
a_dict = { 'e': (1, 100), 'a': (2, 3) }
我无法按元组的第二个元素对其进行排序.生成的字典将显示如下:
I am unable to sort it by the second element of the tuple. The resultant dictionary will appear as below:
a_dict = { 'a': (2, 3), 'e': (1, 100) }
推荐答案
字典不能像这样排序,但是您可以对它们的内容进行排序:
Dictionaries can't be sorted as such, but you can sort their contents:
sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2)
sorted(a_dict.items(), key=lambda item: item[1][1]) # Python 3
您可以将结果放入 collections.OrderedDict
(自2.7开始):
You can put the results into a collections.OrderedDict
(since 2.7):
OrderedDict(sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2))
OrderedDict(sorted(a_dict.items(), key=lambda item: item[1][1]) # Python 3
这篇关于如何按值对Python字典排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文