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

标签 python sorting dictionary

我有一个看起来像这样的字典列表:

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

我需要根据代码键的值对该列表进行排序,但代码的顺序由单独的列表确定:

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

所以最终的列表应该是这样的:

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

有没有人对如何实现这一目标有任何建议?我很难弄清楚如何进行这种排序。

最佳答案

Python 2.7+:

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

年长者:

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

关于python - 根据 Python 中单独列表中键的顺序,按键对字典列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15280603/

相关文章:

c++ - 更好的数组移位算法?

dictionary - .NET : ForEach() extension methods and Dictionary

r - 如何 ddply() 不排序?

php - 如何让用户插入列表中的任意位置?

python - 使用 Dict 创建索引的更快代码

python - 从 Python 中的字典中的列表中删除一个元素

python - 我们如何基于Python中的特定列水平合并四个pandas数据框

python - 每个工作日在两个日期之间出现的次数

python - 安装后没有名为 matplotlib 的模块

python - 在 Python 中将 CSS ":contains:"与 WebDriver 结合使用