如何在Python中对列表内的嵌套字典按Price排序?
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

