0

Having a dict like:

x  = {
  '1': {'a': 1, 'b': 3},
  '2': {'a': 2, 'b': 4}
}

I'd like to have a new key total with the sum of each key in the subdictionaries, like:

x['total'] = {'a': 3, 'b': 7}

I've tried adapting the answer from this question but found no success.

Could someone shed a light?

Onilol
  • 1,315
  • 16
  • 41
  • 2
    Show _how_ you tried adapting the answers from that question, and where and how it fails, and we can help you debug your problem. Because really, your question is the same as that one, except you want to sum up `x.values()` instead of just `x`, so we can’t guess where you might have gotten stuck if you don’t tell us. – abarnert Jun 05 '18 at 19:33

4 Answers4

3

Assuming all the values of x are dictionaries, you can iterate over their items to compose your new dictionary.

from collections import defaultdict

x  = {
  '1': {'a': 1, 'b': 3},
  '2': {'a': 2, 'b': 4}
}

total = defaultdict(int)

for d in x.values():
    for k, v in d.items():
        total[k] += v

print(total)
# defaultdict(<class 'int'>, {'a': 3, 'b': 7})
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
3

A variation of Patrick answer, using collections.Counter and just update since sub-dicts are already in the proper format:

from collections import Counter

x  = {
  '1': {'a': 1, 'b': 3},
  '2': {'a': 2, 'b': 4}
}

total = Counter()

for d in x.values():
    total.update(d)

print(total)

result:

Counter({'b': 7, 'a': 3})

(update works differently for Counter, it doesn't overwrite the keys but adds to the current value, that's one of the subtle differences with defaultdict(int))

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

You can use a dictionary comprehension:

x = {'1': {'a': 1, 'b': 3}, '2': {'a': 2, 'b': 4}}
full_sub_keys = {i for b in map(dict.keys, x.values()) for i in b}
x['total'] = {i:sum(b.get(i, 0) for b in x.values()) for i in full_sub_keys}

Output:

{'1': {'a': 1, 'b': 3}, '2': {'a': 2, 'b': 4}, 'total': {'b': 7, 'a': 3}}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0
from collections import defaultdict
dictionary = defaultdict(int)
x  = {
     '1': {'a': 1, 'b': 3},
     '2': {'a': 2, 'b': 4}
     }

for key, numbers in x.items():
    for key, num in numbers.items():
          dictionary[key] += num

x['total'] = {key: value for key, value in dictionary.items()}
print(x)

We can create a default dict to iterate through each of they key, value pairs in the nested dictionary and sum up the total for each key. That should enable a to evaluate to 3 and b to evaluate to 7. After we increment the values we can do a simple dictionary comprehension to create another nested dictionary for the totals, and make a/b the keys and their sums the values. Here is your output:

{'1': {'a': 1, 'b': 3}, '2': {'a': 2, 'b': 4}, 'total': {'a': 3, 'b': 7}}
Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27