如何对含公共键的嵌套字典列表按键值求和合并?
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
mergeddictionary 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
Counteron 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 (likeaorb).
- If the key isn't in
- 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
相关产品推荐
相关产品推荐

