如何通过两个键对字典列表进行排序,其中第二个键应按降序排序

时间:2014-01-03 05:53:08

标签: python list sorting dictionary

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

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'))

1 个答案:

答案 0 :(得分:1)

我会编写自己的比较函数,因此sorted

中的cmp参数

示例(首先按升序排序,然后按降序秒降序排序):

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引用的帖子中的简化且不太通用的版本。如果您理解这一点,我建议您查看该链接以获得更通用的解决方案。