Sort nested dictionary inside a list in Python?
This question already has an answer here:
data = [ { "PricingOptions": { "Price": 51540.72, "Agents": [ 4056270 ] } }, { "PricingOptions": { "Price": 227243.14, "Agents": [ 4056270],} } ]
newlist = sorted(data, key=lambda k: k['PricingOptions']["Price"])
print(newlist)
Output:
[{'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}]
or in descending order
newlist = sorted(data, key=lambda k: k['PricingOptions']["Price"], reverse=True)
print(newlist)
#[{'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}]
You can use sorted
method by applying a lambda
expression.
sort_list = sorted(data, key=lambda elem: elem['PricingOptions']["Price"])
Output
[{'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}]
If you want to sort
the list descending you just need to assign True
to reverse
property.
上一篇: 使用列表中的项目对列表进行排序
下一篇: 在Python中的列表中排序嵌套的字典?