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

Python新手求助:如何优雅实现JSON数组按值升序排序及键名修改

Solution for Sorting and Renaming Keys in a Python Dictionary List

Hey there! Let's walk through how to solve this problem in a clean, Pythonic way—perfect for a new learner to grasp. Here's the step-by-step breakdown:

Step 1: Rename the 'path' key to 'path_old'

First, we'll create a new list of dictionaries where each entry replaces the path key with path_old. Using a list comprehension is the most elegant way to do this in Python—it's concise and readable.

Step 2: Sort by the 'val' value (ascending order)

Next, we'll sort this new list using Python's built-in sorted() function. Since val is a list with a single numeric value, we'll use a lambda function to target that first element as our sorting key.

Full Code Example

# Your input list
input_list = [
    {'path': 'file_abc.wav', 'val': [0.49]},
    {'path': 'file_dfg.wav', 'val': [0.0]},
    {'path': 'file_ejh.wav', 'val': [1.0]}
]

# Combine renaming and sorting in one clean step
sorted_result = sorted(
    # Rename 'path' to 'path_old' for each item
    [{'path_old': item['path'], 'val': item['val']} for item in input_list],
    # Sort by the first element in the 'val' list, ascending
    key=lambda x: x['val'][0]
)

# Print the result to verify
print(sorted_result)

Output

[{'path_old': 'file_dfg.wav', 'val': [0.0]}, {'path_old': 'file_abc.wav', 'val': [0.49]}, {'path_old': 'file_ejh.wav', 'val': [1.0]}]

Explanation

  • List Comprehension: The [{'path_old': item['path'], ...} for item in input_list] part iterates over each dictionary in your input, creates a new dictionary with the renamed key, and keeps the original val intact.
  • sorted() with Lambda: The key=lambda x: x['val'][0] tells Python to use the first element of the val list as the value to sort by. By default, sorted() sorts in ascending order, which matches your desired output.

Bonus: Handling Edge Cases

If there's a chance some entries might have an empty val list, you can adjust the lambda to handle that gracefully (e.g., default to 0 if empty):

key=lambda x: x['val'][0] if x['val'] else 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:15:40