根据列表中的元素对以列表为值的字典进行排序 [英] Sorting a dictionary with lists as values, according to an element from the list
问题描述
我想按每个列表中的第三项对列表字典进行排序.当值只是一个数字或字符串时,按值对字典排序很容易,但是这个列表让我感到困惑.
I want to sort a dictionary of lists, by third item in each list. It's easy enough sorting a dictionary by value when the value is just a single number or string, but this list thing has me baffled.
示例:
myDict = {'item1': [7, 1, 9], 'item2': [8, 2, 3], 'item3': [9, 3, 11] }
我希望能够按照每个列表中第三个值的顺序遍历字典,在这种情况下,依次为 item2
, item1
和 item3 代码>.
I want to be able to iterate through the dictionary in order of the third value in each list, in this case item2
, item1
then item3
.
推荐答案
这里是执行此操作的一种方法:
Here is one way to do this:
>>> sorted(myDict.items(), key=lambda e: e[1][2])
[('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])]
的
函数使您可以为列表的每个元素派生一个排序键. key
参数> sorted
The key
argument of the sorted
function lets you derive a sorting key for each element of the list.
要遍历此列表中的键/值,可以使用类似以下内容的
To iterate over the keys/values in this list, you can use something like:
>>> for key, value in sorted(myDict.items(), key=lambda e: e[1][2]):
... print key, value
...
item2 [8, 2, 3]
item1 [7, 1, 9]
item3 [9, 3, 11]
这篇关于根据列表中的元素对以列表为值的字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!