python - 使用另一个列表作为 "filter"对 python 中的字典列表进行排序?

标签 python dictionary

b = [{'id': 'a'}, {'id': 'c'}, {'id': 'b'}, {'id': 'e'}]

我需要这个变成:

b = [{'id': 'a'}, {'id': 'c'}, {'id': 'e'}, {'id': 'b'}]

这个新订单由另一个列表定义。

my_filter = ['a', 'c', 'e', 'b']

...如您所见,带有字典的列表现在有一系列 ID,这些 ID 显示在 my_filter 变量上。

我可以重新排序,但使用一堆 fors 效率不高。你知道更好的方法吗?我已经知道如何sort a list of dictionaries by values of the dictionary , 但我需要这个订单由另一个列表定义。

编辑:my_filter 被命名为filter,我在Dave Kirby's recommendation 之后更改了因为它是内置的。由于某些答案中仍然包含 filter,因此如果您在其中一些答案中看到 filter,此编辑部分是为了避免混淆。

最佳答案

>>> sorted(b, key=lambda x: filter.index(x['id']))
[{'id': 'a'}, {'id': 'c'}, {'id': 'e'}, {'id': 'b'}]

关于python - 使用另一个列表作为 "filter"对 python 中的字典列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6686455/

相关文章:

c# - 为什么 C# Dictionary 不实现所有 IDictionary?

python - 如何基于 Flask mega 教程在 pythonanywhere 上设置 Flask

python - Python 中的 TCP 发送错误 - 套接字的协议(protocol)类型错误

python - Visual Studio 中的 Windows 窗体与 Python

python - 从字典中提取键值作为数据框

python - Python 中的任意字典 (JSON) 到更严格的树状字典 (JSON)

python - RDFLib 空白节点打印

python - 如何使用用户输入结束程序?

python - 在 python 中反转 dict 和访问它的值的正确方法是什么?

mongodb - 禁用 Go mongo bson map 中的某些字段