计算总价值dict

calculate the total value dict

我有一个问题,如何计算相同键的总dict?我有一个字典:

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

我希望结果为:

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

非常感谢

很简单:

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

... d 是你的 dict 并且没有任何错误检查(密钥是否存在,它是否真的是一个数字,等等)。


作为具有理解力的整个代码片段:

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)

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