Python新手求助:如何优雅实现JSON数组按值升序排序及键名修改
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 originalvalintact. - sorted() with Lambda: The
key=lambda x: x['val'][0]tells Python to use the first element of thevallist 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

