简体   繁体   中英

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

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 .

您可以使用字典理解来添加嵌套在字典d中的所有数字,如下所示:

totals = {k: sum(v.get(k, 0) for v in d.values()) for k in d.values()[0]} # dict of totals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM