【问题标题】:Sort list of dictionaries according to the list of values根据值列表对字典列表进行排序
【发布时间】:2021-08-18 20:25:23
【问题描述】:

词典列表:

 list_dict = [{'a': 'car', 'b': 4}, {'a': 'train', 'b': 10}, {'a': 'flight', 'b': 6}, {'a': 'bike', 'b': 2}]

我想根据值列表对带有 a 键的字典列表进行排序:

a_list = ["flight", "bike", "train", "car"]

我想要的输出:

[{'a': 'flight', 'b': 6}, {'a': 'bike', 'b': 2}, {'a': 'train', 'b': 10}, {'a': 'car', 'b': 4}]

最好不要为解决方案使用任何循环。

【问题讨论】:

标签: python pandas list dictionary


【解决方案1】:
list_dict.sort(key=lambda x:a_list.index(x['a']))

【讨论】:

  • @OP - 请注意,上面的答案对 dict 就地进行了排序
【解决方案2】:

试试:

print(sorted(list_dict, key=lambda k: a_list.index(k["a"])))

打印:

[
    {"a": "flight", "b": 6},
    {"a": "bike", "b": 2},
    {"a": "train", "b": 10},
    {"a": "car", "b": 4},
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多