按另一个列表对词典列表进行排序 [英] Sort list of dictionaries by another list

查看:91
本文介绍了按另一个列表对词典列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用另一个列表对词典列表进行排序. 我有带字典的列表(IN),我想按另一个列表(sortValue)排序.

Sort list of dictionaries by another list. I have got list with dictionaries (IN) and I want to sort this by another list (sortValue).

IN = [{
        "id": "a", 
        "val": "Value", 
        "val1": "Value1"
 }, 
 {
        "id": "b", 
        "val": "Value", 
        "val1": "Value1"
 }, 
 {
        "id": "c", 
        "val": "Value", 
        "val1": "Value1"
 }]

sortValue = ['b','c','a']

我想要输出

OUT  = [{
        "id": "b", 
        "val": "Value", 
        "val1": "Value1"
    }, 
    {
        "id": "c", 
        "val": "Value", 
        "val1": "Value1"
    },
    {
        "id": "a", 
        "val": "Value", 
        "val1": "Value1"
    }]

如何获得这样的东西?

我尝试过:

OUT = []
for xx in sortValue:
    for x in IN:
        if x['id'] == xx:
            OUT.append(x)
print OUT
del OUT

但是dict的价值参差不齐. [{'val1':'Value1','id':'b','val':'Value'}},{'val1':'Value1','id':'c','val':'Value '},{'val1':'Value1','id':'a','val':'Value'}]

But value in dict is mixed. [{'val1': 'Value1', 'id': 'b', 'val': 'Value'}, {'val1': 'Value1', 'id': 'c', 'val': 'Value'}, {'val1': 'Value1', 'id': 'a', 'val': 'Value'}]

推荐答案

您还可以使用sorted函数的key参数.对于您的情况,您需要列表中每个项目的id的sortValue索引:

You can also use the key parameter of the sorted function. In your case, you want the index of sortValue for the id of each item on the list:

>>> pprint(sorted(IN,key=lambda x:sortValue.index(x['id'])))
[{'id': 'b', 'val': 'Value', 'val1': 'Value1'},
 {'id': 'c', 'val': 'Value', 'val1': 'Value1'},
 {'id': 'a', 'val': 'Value', 'val1': 'Value1'}]

有关在 wiki 上使用python进行排序的更多信息.

More on sorting with python on its wiki.

这篇关于按另一个列表对词典列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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