简体   繁体   English

根据Python中单独列表中键的顺序,按键对字典列表进行排序

[英]Sort a list of dictionaries by a key, based on the order of keys in a separate list in Python

I have a list of dictionaries which looks something like this: 我有一个字典列表,看起来像这样:

[
    {
        "format": "format1",
        "code": "tr"
    },
    {
        "format": "format2",
        "code": "hc"
    },
    {
        "format": "format3",
        "code": "bx"
    },
    {
        "format": "format4",
        "code": "mm"
    },
    {
        "format": "format5",
        "code": "el"
    }
]

I need to order this list based on the value of the code key, but the order of the codes is determined by a separate list: 我需要根据代码键的值来排序此列表,但代码的顺序由单独的列表确定:

code_order = ["mm", "hc", "el", "tr", "bx"]

So the final list should look like this: 所以最终的列表应如下所示:

[
    {
        "format": "format4",
        "code": "mm"
    },
    {
        "format": "format2",
        "code": "hc"
    },
    {
        "format": "format5",
        "code": "el"
    },
    {
        "format": "format1",
        "code": "tr"
    },
    {
        "format": "format3",
        "code": "bx"
    }
]

Does anyone have any suggestions on how to achieve this? 有没有人对如何实现这一点有任何建议? I'm having a difficult time figuring out how to do this kind of sort. 我很难弄清楚如何做这种事情。

Python 2.7+: Python 2.7+:

lookup = {s: i for i, s in enumerate(code_order)}
print(sorted(l, key=lambda o: lookup[o['code']]))

Older: 老年人:

lookup = dict((s, i) for i, s in enumerate(code_order))
print sorted(l, key=lambda o: lookup[o['code']])

If l is your list of dicts, then 如果l是你的dicts列表,那么

sorted(l, key=lambda d: code_order.index(d['code']))

should do the trick. 应该做的伎俩。 Read that as: 阅读如下:

key is the function that looks up code in the given dict d , then checks the index of that code in code_order , so the final sort is by those indices. key是在给定dict d中查找code ,然后在code_order检查该代码的索引的code_order ,因此最后的排序是通过这些索引进行的。

(If code_order gets really large, then keep in mind that list.index takes linear time so you'd better replace it by a dict. But for this short code_order , it shouldn't matter.) (如果code_order真的很大,请记住list.index需要线性时间,所以最好用字典代替它。但是对于这段简短的code_order ,没关系。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM