【问题标题】:How to do sorting in Python3 for a list dictionary inside?如何在 Python3 中对里面的列表字典进行排序?
【发布时间】:2021-09-07 04:45:22
【问题描述】:

我有一个字典列表如下:

[{"A":5,"B":10},

{"A":6,"B":13},

{"A":10,"B":5}]

我想按B 的值降序排列此列表。输出应如下所示:

[{"A":6,"B":13},

{"A":5,"B":10},

{"A":10,"B":5}]

怎么做?

【问题讨论】:

标签: python-3.x list sorting dictionary


【解决方案1】:

您可以根据对每个元素应用函数的结果对列表进行排序:https://docs.python.org/3.9/library/functions.html#sorted

>>> data = [{"A":5,"B":10},
...     {"A":6,"B":13},
...     {"A":10,"B":5}]
>>> sorted(data, key=lambda dct: dct["B"], reverse=True)
[{'A': 6, 'B': 13}, {'A': 5, 'B': 10}, {'A': 10, 'B': 5}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多