Mezo
Mezo

Reputation: 43

Sorting array in dictionary in python by specific key value

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} ] 
}

Upvotes: 0

Views: 925

Answers (1)

P. Leibner
P. Leibner

Reputation: 473

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.

Upvotes: 1

Related Questions