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} ] 
}
Mezo
  • 163
  • 1
  • 20
  • See the `key` parameter of [sorted](https://docs.python.org/3/library/functions.html#sorted) – Dani Mesejo Nov 21 '20 at 12:50
  • 1
    have a look at this answer: https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – Gregory Nov 21 '20 at 13:01
  • 1
    Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – ashraful16 Nov 21 '20 at 13:02

1 Answers1

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.

P. Leibner
  • 434
  • 4
  • 16