如何基于键值编辑嵌套字典的值并构建对应处理函数
Got it, let's break this down! Since you already have a working function for flat dictionaries, the main trick to extend it to nested ones is recursion—it lets us dive into every nested dictionary just like we would a top-level one, repeating the logic until we hit non-dict values.
First, Let's Recap the Flat Dictionary Version
Just to align, here's what your existing function might look like (for reference):
def add_sum_flat(d, target_key, new_key): total = d.get(target_key, 0) d[new_key] = total return d
Simple enough—grab the target value, add a new key with that value. Now let's build on this.
The Recursive Nested Version
Here's a function that traverses every level of nested dictionaries, sums up all instances of your target key, and adds the total as a new key at each level:
import copy def add_nested_sum(d, target_key, new_key): # Create a deep copy to avoid modifying the original dictionary (optional but safe) working_dict = copy.deepcopy(d) # Calculate the total for the current dictionary level current_total = working_dict.get(target_key, 0) # Iterate through all values to find nested dictionaries for key, value in working_dict.items(): if isinstance(value, dict): # Recursively process the nested dictionary nested_dict = add_nested_sum(value, target_key, new_key) # Add the nested total to the current level's total current_total += nested_dict.get(target_key, 0) # Add the new key with the computed total working_dict[new_key] = current_total return working_dict
How This Works:
- Deep Copy: Using
copy.deepcopyensures we don't alter your original dictionary—remove this if you want to modify the original directly. - Current Level Total: Starts with the target key's value in the current dictionary (0 if it doesn't exist).
- Recursion Check: For every value that's a dictionary, we call the same function on it. This lets us dig into every nested layer.
- Sum Accumulation: We add the target key's value from each processed nested dictionary to the current level's total.
- New Key Addition: Finally, we attach the total as the new key to the current dictionary.
Test It Out!
Let's use a sample nested dictionary to see it in action:
sample_dict = { "score": 10, "section": { "score": 5, "sub_section": { "score": 3 } }, "notes": "Test data" } # Add a "total_score" key that sums all "score" values at each level result = add_nested_sum(sample_dict, "score", "total_score") print(result)
Output:
{ "score": 10, "section": { "score": 5, "sub_section": { "score": 3, "total_score": 3 }, "total_score": 8 # 5 + 3 }, "notes": "Test data", "total_score": 18 # 10 + 5 + 3 }
Customization Tips
- Skip Current Level: If you don't want to include the current dictionary's target value in the total, start
current_totalat 0 instead ofworking_dict.get(target_key, 0). - Handle Other Iterables: If your data has lists of dictionaries, add a check for
isinstance(value, list)and loop through each item to process nested dicts inside lists. - Non-Numeric Values: Add a check like
if isinstance(current_total, (int, float))to avoid errors if the target key has non-numeric values.
内容的提问来源于stack exchange,提问作者David

