如何实现嵌套Python字典中相同键的值累加堆叠?
First, let's break down your requirement: you need to maintain a running total for each key across the nested dictionaries in your outer dict, updating each subsequent nested dict's values to reflect the cumulative sum up to that point.
Here's a straightforward approach using a cumulative tracker dictionary to keep track of sums as we iterate through your original data:
Step-by-Step Implementation
# Your original dictionary original_dict = { 2: {510: 8.5, 525: 6.8, 540: 9.5}, 3: {525: 6.8, 540: 9.5}, 4: {525: 6.8, 540: 9.5, 570: 8.7, 585: 10.7, 600: 10.2}, 7: {600: 10.2, 615: 10.1} } # Initialize a tracker to keep cumulative sums for each key cumulative_tracker = {} # Initialize the result dictionary result_dict = {} # Iterate through each item in the original dictionary (preserves order in Python 3.7+) for outer_key, nested_dict in original_dict.items(): updated_nested = {} for key, value in nested_dict.items(): # Update the cumulative sum for this key: add current value to existing sum (or 0 if new) cumulative_tracker[key] = cumulative_tracker.get(key, 0) + value # Assign the cumulative sum as the new value in the current nested dict updated_nested[key] = cumulative_tracker[key] # Add the updated nested dict to the result result_dict[outer_key] = updated_nested # Print the result to verify print(result_dict)
Output
{ 2: {510: 8.5, 525: 6.8, 540: 9.5}, 3: {525: 13.6, 540: 19.0}, 4: {525: 20.4, 540: 28.5, 570: 8.7, 585: 10.7, 600: 10.2}, 7: {600: 20.4, 615: 10.1} }
How This Works
- Cumulative Tracker: The
cumulative_trackerdict keeps a running total for every key we've encountered so far. For each key in the current nested dict, we usecumulative_tracker.get(key, 0)to safely get the existing sum (or 0 if the key is new), then add the current value to it. - Update Nested Dict: For each key in the current nested dict, we set its value to the updated cumulative sum from the tracker.
- Preserve Order: Since Python 3.7+, dictionaries preserve insertion order, so we process the outer keys in the same order they appear in your original dict. If you're using an older Python version, you can sort the outer keys explicitly (e.g.,
sorted(original_dict.keys())) before iterating.
Why Your Previous Approach Might Have Failed
Storing values in lists and trying to add them to the next dict can work, but it's easy to lose track of the running total if you're not updating a single cumulative store. This approach simplifies things by maintaining one source of truth for each key's accumulated value, ensuring we always have the latest sum to add to the next occurrence of the key.
内容的提问来源于stack exchange,提问作者eicul04

