根据列表中的元素对以列表为值的字典进行排序 [英] Sorting a dictionary with lists as values, according to an element from the list

查看:55
本文介绍了根据列表中的元素对以列表为值的字典进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按每个列表中的第三项对列表字典进行排序.当值只是一个数字或字符串时,按值对字典排序很容易,但是这个列表让我感到困惑.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆