0

I have a problem, how to calculate the total dict of the same keys ? I have a dict:

{'learning': {'DOC1': 0.14054651081081646,
              'DOC2': 0,
              'DOC3': 0.4684883693693881},
 'life':     {'DOC1': 0.14054651081081646, 
              'DOC2': 0.20078072972973776, 
              'DOC3': 0}
}

and I hope the results as:

{'learning life': {
        'DOC1': DOC1 in learning + DOC1 in life,
        'DOC2': DOC2 in learning + DOC2 in life,
        'DOC3': DOC3 in learning + DOC3 in life,}}

Thank you very much

Yanwar Sky
  • 751
  • 7
  • 10
  • Possible duplicate of [Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?](http://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe) – Querenker Sep 26 '16 at 21:20

2 Answers2

1

Pretty simple:

for k in d['learning']:
    print(d['learning'][k] + d['life'][k])

... with d being your dict and no error checking whatsoever (does the key exist, is it really a number, etc.).


As whole code snippet with a comprehension:
d = {'learning': {'DOC1': 0.14054651081081646,
              'DOC2': 0,
              'DOC3': 0.4684883693693881},
 'life':     {'DOC1': 0.14054651081081646, 
              'DOC2': 0.20078072972973776, 
              'DOC3': 0}
}

d['sum'] = [d['learning'][k] + d['life'][k]
            for k in d['learning']]
print(d)

See a demo on ideone.com.

Jan
  • 42,290
  • 8
  • 54
  • 79
  • 1
    Of course, that implies that the exact same keys that are in `learning` are also in `life`. If you have different key values, you also have to check whether the key in `learning` is in `life`. This can be done by using `for key in learning.keys()` and `if key in life.keys()` – S. Gamgee Sep 26 '16 at 21:20
0

You can use a dictionary comprehension to add all the numbers nested in a dictionary d just like so:

totals = {k: sum(v.get(k, 0) for v in d.values()) for k in d.values()[0]} # dict of totals
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70