【问题标题】:How can I sort a list of dictionary by two keys, in which the second key should be sorted in descending order [duplicate]如何按两个键对字典列表进行排序,其中第二个键应按降序排序[重复]
【发布时间】:2014-01-03 05:53:07
【问题描述】:

如何按两个键对字典列表进行排序,其中第二个键应按降序排序。 我有一个包含许多字典的列表,格式为:

result = [{'so':ABC,'so_value':123.0,'inv':'ADV-025'},
{'so':PQR,'so_value':19.0,'inv':'908025'}]

我想通过键“so”(升序)和“inv”(降序)对列表进行排序。如何在 python 中使用itemgetter 做到这一点?

  • 编辑:

    我尝试了以下方法,但它只会按升序排序。 result = sorted(result, key=itemgetter('so', 'inv'))

【问题讨论】:

  • 你有没有尝试过?
  • @Christian 我尝试了以下方法,但它只会按升序排序。 result = sorted(result, key=itemgetter('so', 'inv'))
  • @GopakumarNG 也将其添加到问题中,否则可能会毫不费力地关闭。
  • 并发布预期的输出。
  • 请注意,在上面的 SO 帖子中,我说过这是重复的,接受的答案提供了一种按 任意 个键或某些键进行排序的方法可以通过在密钥前面加上 - (减号)符号来“否定”(反转)。我相信这完全涵盖了您的情况

标签: python list sorting dictionary


【解决方案1】:

我会编写自己的比较函数,所以 sorted 中的 cmp 参数

示例(先按 so 升序排序,按 inv 降序排序):

from operator import itemgetter

input = [{'so':'PQR','so_value':19.0,'inv':'908025'},{'so':'ABC','so_value':123.0,'inv':'ADV-025'}]

def compare(x, y):
    (xso, xinv) = x
    (yso, yinv) = y
    socmp = cmp(xso,yso) #compare so
    if socmp == 0: #if so are equal, compare inv
        return -cmp(xinv, yinv) #minus for descending order
    else:
        return socmp

print sorted(input, cmp=compare, key=itemgetter('so','inv'))

请注意,这基本上是three_pineapples 引用的帖子中的一个简化且不太通用的版本。如果您理解这一点,我建议您查看该链接以获得更通用的解决方案。

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2021-12-20
    • 2020-12-04
    • 2013-11-02
    相关资源
    最近更新 更多