简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM