Search code examples
pythonlistdictionarysortingkey

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.


Solution

  • 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']])