Yanwar Solahudin Yanwar Solahudin - 1 year ago 68
Python Question

calculate the total value dict

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download