在Python中的列表中排序嵌套的字典?
这个问题在这里已经有了答案:
data = [ { "PricingOptions": { "Price": 51540.72, "Agents": [ 4056270 ] } }, { "PricingOptions": { "Price": 227243.14, "Agents": [ 4056270],} } ]
newlist = sorted(data, key=lambda k: k['PricingOptions']["Price"])
print(newlist)
输出:
[{'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}]
或按降序排列
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]}}]
您可以通过应用lambda
表达式来使用sorted
方法。
sort_list = sorted(data, key=lambda elem: elem['PricingOptions']["Price"])
产量
[{'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}]
如果你想按降序对列表进行sort
,你只需要指定True
来reverse
属性。
上一篇: Sort nested dictionary inside a list in Python?
下一篇: Sorting a list of dictionaries by a specific dictionary key