Skip to content
Advertisement

How to do a multi level sort on list of lists in Python? [duplicate]

I have the below code:

lst = [['candy','30'], ['apple','10'], ['baby','20'], ['baby','10']]
lst.sort(key=lambda x: (x[1], x[0]))
print(lst)

With this the output is:

[['apple', '10'], ['baby', '10'], ['baby', '20'], ['candy', '30']]

I’m trying to display the names in Descending order while the values in Ascending order. Is there a pre built way in python to achieve this?

Expected output:

[['baby', '10'], ['apple', '10'], ['baby', '20'], ['candy', '30']]

Advertisement

Answer

You changed the expected output, this would be the solution for that:

lst.sort(key=lambda x: (-int(x[1]), x[0]), reverse=True)
#[['baby', '10'], ['apple', '10'], ['baby', '20'], ['candy', '30']]

This was the answer before the question was edited and seperates the entries before sorting them:

print(*zip(sorted([x[0] for x in lst], reverse=True), sorted([x[1] for x in lst])))
# ('candy', '10') ('baby', '10') ('baby', '20') ('apple', '30')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement