You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中对列表内的嵌套字典按Price排序?

Sorting by Nested Price Field in a List of Dictionaries

First, let's restate your input data for clarity:

original_list = [
    { "PricingOptions": { "Price": 51540.72, "Agents": [4056270] } },
    { "PricingOptions": { "Price": 227243.14, "Agents": [4056270] } }
]

To sort this list based on the Price field inside each PricingOptions dictionary, you can use Python's built-in sorting tools with a custom key that extracts the nested price value. Here's how to do it:

Ascending Order (Lowest to Highest Price)

Use the sorted() function with a lambda function as the key to access the nested Price attribute. This returns a new sorted list without modifying the original:

sorted_ascending = sorted(original_list, key=lambda item: item['PricingOptions']['Price'])

Descending Order (Highest to Lowest Price)

Add the reverse=True parameter to flip the sort direction:

sorted_descending = sorted(original_list, key=lambda item: item['PricingOptions']['Price'], reverse=True)

Sorting In-Place

If you want to modify the original list directly instead of creating a new one, use the list's .sort() method with the same key logic:

# Sort ascending in-place
original_list.sort(key=lambda item: item['PricingOptions']['Price'])

# Sort descending in-place
original_list.sort(key=lambda item: item['PricingOptions']['Price'], reverse=True)

Handling Missing Keys (Optional)

If some items in your list might not have the PricingOptions or Price keys (to avoid KeyError), you can add a fallback value in the lambda:

# Default to 0 if keys are missing
sorted_safe = sorted(original_list, key=lambda item: item.get('PricingOptions', {}).get('Price', 0))

内容的提问来源于stack exchange,提问作者Ajay Shewale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:50:57