0

I have the following dictionary:

products = { 
'count': 3, 
'items': [ {'order': 2, 'name': green}, 
           {'order': 1, 'name': red}, 
           {'order': 3, 'name': blue} ] 
}

how can I sort the dictionary by the value of 'order' from highest to lowest so it results like this:

products = { 
'count': 3, 
'items': [ {'order': 3, 'name': blue}, 
           {'order': 2, 'name': green}, 
           {'order': 1, 'name': red} ] 
}
3

1 Answer 1

1

Items contains a list of orders, so you can apply .sort() with a lambda function on your list:

products["items"].sort(key=lambda x: x["order"], reverse=True)

Reverse is True because you want a descending order.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.