根据字典中列表值的第二项,以列表作为值对字典列表进行排序 [英] Sorting list of dictionaries with list as values based on second item of list value in dictionary

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

问题描述

我有一个包含字典的列表,在每个字典中,值的列表也很像:

a = [{"25.21" : [400,500] , "25.22" : [700,502]} , {"12.15" : [350,800] , "12.13" : [750,803]}]

我想根据列表的第二项对主列表进行排序,第二项是字典的值,而字典的值又是主列表的一项.输出应为:

a = [ {"12.13" : [750,803] , "12.15" : [350,800] } , {"25.22" : [700,502], "25.21" : [400,500] }]

作为字典中每个键的值的列表的第一项将有所不同.如果可能的话,如何在不使用操作符itemgetter的情况下在oneliner中做到这一点?

此问题与此问题不同一个.在这种情况下,列表内的字典值仅包含整数,因为该问题将列表作为主列表内的字典值.

解决方案

使用sorted

演示:

a = [{"25.21" : [400,500] , "25.22" : [700,502]} , {"12.15" : [350,800] , "12.13" : [750,803]}]

print(sorted(a, key=lambda x: list(x.items())[1][1], reverse=True))
#print(sorted(a, key=lambda x: x.items()[1][1], reverse=True))   #python2

输出:

[{'12.15': [350, 800], '12.13': [750, 803]}, {'25.21': [400, 500], '25.22': [700, 502]}]

I've a list which contains dictionaries and in each dictionaries the values are also list like :

a = [{"25.21" : [400,500] , "25.22" : [700,502]} , {"12.15" : [350,800] , "12.13" : [750,803]}]

I want to sort the main list according to the second item of the list which is the value of the dictionary which is again an item of the main list. The output should be like :

a = [ {"12.13" : [750,803] , "12.15" : [350,800] } , {"25.22" : [700,502], "25.21" : [400,500] }]

The first item of the list as values for each key inside dictionary would be different. How to do that in an oneliner if possible without using operator itemgetter?

This question is not same as this one. In that case, the values of the dictionary inside the list contained only integers where as this question has list as values of dictionaries inside the main list.

解决方案

Using sorted

Demo:

a = [{"25.21" : [400,500] , "25.22" : [700,502]} , {"12.15" : [350,800] , "12.13" : [750,803]}]

print(sorted(a, key=lambda x: list(x.items())[1][1], reverse=True))
#print(sorted(a, key=lambda x: x.items()[1][1], reverse=True))   #python2

Output:

[{'12.15': [350, 800], '12.13': [750, 803]}, {'25.21': [400, 500], '25.22': [700, 502]}]

这篇关于根据字典中列表值的第二项,以列表作为值对字典列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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