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

如何对含公共键的嵌套字典列表按键值求和合并?

Merging Nested Dictionaries with Summed Values

The problem with using Counter directly on the top-level dictionaries is that it replaces existing values instead of handling the nested key-value sums. Since your data has two levels of nesting, we need to apply Counter to the inner dictionaries to correctly accumulate the values.

Here's a working solution:

from collections import Counter

ps = [{'one': {'a': 30, "b": 30}, 'two': {'a': -1000}}, {'three': {'a': 44}, 'one': {'a': -225}}, {'one': {'a': 2000, "b": 30}}]

merged = {}

# Iterate through each dictionary in the list
for item in ps:
    # Process each top-level key and its nested dictionary
    for top_key, inner_dict in item.items():
        # Initialize the top-level key with a Counter if it doesn't exist
        if top_key not in merged:
            merged[top_key] = Counter(inner_dict)
        else:
            # Update the existing Counter with the new inner dictionary values (sums them)
            merged[top_key].update(Counter(inner_dict))

# Convert inner Counters back to regular dictionaries for the final result
result = {key: dict(counter) for key, counter in merged.items()}

print(result)

How this works:

  • We start with an empty merged dictionary to build our result.
  • For each dictionary in the input list, we loop through its top-level keys (like one, two).
  • For each top-level key, we use Counter on the inner dictionary:
    • If the key isn't in merged, we add it with a Counter of the inner dict.
    • If it is present, we call update() on the existing Counter, which automatically sums the values for matching inner keys (like a or b).
  • Finally, we convert the inner Counters back to regular dictionaries to match your desired output format.

Running this code will produce exactly the nested dictionary you want:

{"one": {"a": 1805, "b": 60}, "two": {"a": -1000}, "three": {"a": 44}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:14:28