简体   繁体   English

按特定键值对python字典中的数组进行排序

[英]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: Items 包含一个订单列表,因此您可以将 .sort() 与列表中的 lambda 函数一起应用:

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

Reverse is True because you want a descending order. Reverse 为 True,因为您想要降序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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