BananaMaster
BananaMaster

Reputation: 567

How to combine sorting parameters in lists?

I have 1 list that goes like this:

list = [{'day':'1','month':'2'},{'day':'3','month':'3'},{'day':'2','month':'6'},{'day':'1','month':'1'}]

and I want to sort it by month first and day after, so that for example (day=1 and month=2) > (day=5 and month=1).

The output of the above list would become:

list = [{'day':'1','month':'1'},{'day':'1','month':'2'},{'day':'3','month':'3'},{'day':'2','month':'6'}]

I tried

sorted(list, key= lambda i: i['month'+'day'])

but this doesn't work.

Upvotes: 1

Views: 39

Answers (1)

yatu
yatu

Reputation: 88276

You need to specify a tuple with the fields you want to order by. Also note that you need to cast the values to int, otherwise the order will be lexicographic, which would imply that for instance '12' < '9'. So:

l = [{'day':'1','month':'2'},{'day':'3','month':'3'},{'day':'2','month':'6'},
     {'day':'1','month':'1'}]

sorted(l, key=lambda x: (int(x['month']), int(x['day'])))

[{'day': '1', 'month': '1'},
 {'day': '1', 'month': '2'},
 {'day': '3', 'month': '3'},
 {'day': '2', 'month': '6'}]

Upvotes: 3

Related Questions