0

listOfDict = [{"sal":1000,"age":25},{"sal":1000,"age":24}, {"sal":1000,"age":26},{"sal":2000,"age":25},{"sal":3000,"age":24}]

Expected o/p : [{"sal":3000,"age":24}, {"sal":2000,"age":25}, {"sal":1000,"age":24}, {"sal":1000,"age":25},{"sal":1000,"age":26}]

I want to sort this in decreasing order of salary and increasing order of age.

I tried c++ style like this:

def auxsort(p1data, p2data):   
    if p1data['sal'] > p2data['sal']:   
        return True
    if p1data['age'] <= p2data['age']:
        return True
    return False

sorted(listOfDict,key=auxsort)

But this is not allowed in python. TypeError: auxsort() takes exactly 2 arguments (1 given)

How to solve this? Thank you

Vicky Gupta
  • 576
  • 6
  • 13
  • https://docs.python.org/3.5/library/functions.html#sorted: "key specifies a function of one argument that is used to extract a comparison key from each list element". Also, your `auxsort` returns `None` (instead of False) if both conditionals fail. – Leporello May 15 '19 at 16:03

1 Answers1

1

You used the key wrong. It should take an element from listOfDict and return something that can directly compare against each other. I suggest the following instead:

def auxsort(p1data): 
    return (-p1data['sal'], p1data['age'])

this returns a tuple of two elements. If tuples t1 < t2 is means the element they correspond to also have such ordering in the sorted output.

wim
  • 338,267
  • 99
  • 616
  • 750
adrtam
  • 6,991
  • 2
  • 12
  • 27