0

How can I sort a list of dictionary by two keys, in which the second key should be sorted in descending order. I have a list which contains a number of dictionaries, the format is:

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

I want to sort the list by keys 'so' (ascending) and 'inv'(descending). How can I do this with itemgetter in python?

  • EDIT:

    I have tried the following but it will sort only by ascending order. result = sorted(result, key=itemgetter('so', 'inv'))

Community
  • 1
  • 1
Gopakumar N G
  • 1,775
  • 1
  • 23
  • 40

1 Answers1

1

I'd write my own compare function, so the cmp argument in sorted

Example (sorted on so ascending first, and on inv descending second):

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

Note that this is basically a simplified and less general version of the one in the post referenced by three_pineapples. If you understand this, I'd advise you to look at that link for a more general solution.

HSquirrel
  • 839
  • 4
  • 16