【发布时间】:2021-11-15 16:30:00
【问题描述】:
所以,我有一个 Python 中的字典列表,如下所示:
lis =
[
{'action': 'Notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'},
{'action': 'Notify', 'type': 'Something Else', 'Genre': 20, 'date': '2021-05-07 01:59:37'}
...
]
现在我希望lis 以某种方式使用,以便每个单独的字典 使用mapping 对我将提供的键进行排序。例如,如果
mapping = {1:'date', 2:'Genre', 3:'action', 4:'type'}
然后,我想让我的原始字典列表如下所示:
lis =
[
{'date': '2021-05-07 01:59:37', 'Genre': 10, 'action': 'Notify', 'type': 'Something'},
{'date': '2021-05-07 01:59:37', 'Genre': 20, 'action': 'Notify', 'type': 'Something Else'}
...
]
我该如何实现?
【问题讨论】:
-
所以你想自定义排序你的字典?
-
是的,没错。
-
Python dicts 最初是无序的。在某些时候发生了更改,以便它们保持添加键的顺序。虽然对订单的控制很弱。如果要更改它,则需要创建一个新列表,按所需顺序添加键,或者您可以删除它们并从现有字典中重新添加它们。
-
为什么不使用列表进行映射?
-
你的映射是向后的...
标签: python list sorting dictionary mapping