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

如何实现嵌套Python字典中相同键的值累加堆叠?

Solution to Accumulate Values in Nested Python Dictionaries

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

  1. Cumulative Tracker: The cumulative_tracker dict keeps a running total for every key we've encountered so far. For each key in the current nested dict, we use cumulative_tracker.get(key, 0) to safely get the existing sum (or 0 if the key is new), then add the current value to it.
  2. Update Nested Dict: For each key in the current nested dict, we set its value to the updated cumulative sum from the tracker.
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:17:36