简体   繁体   中英

calculate sum of product between values in a dictionary and the other nested dictionary

I want to calculate the sum of product between values of dictionary A and the values in nested dictionary B. To be specific,

Dict_A = {'Apple': 0.909, 'Pear': 0.091}
Dict_B = {'Egg': {'a': 0.69, 'b': 0.31},'Bread': {'a': 0.96, 'c': 0.04}}

Apple corresponds with Egg, Pear corresponds with Bread.

I hope to multiply Apple by a and b in Egg, and multiply Pear by a and c in Bread, and finally, I hope to find the sum of same a, b, and c. So the output should be:

OUTPUT = {'a': 0.717, 'b': 0.279, 'c': 0.004}
*where:
a = 0.909*0.69 + 0.091*0.96
b = 0.909*0.31
c = 0.091*0.04

I referred to a relevant question in this link: how to calculate percentage with nested dictionary , which both aim to solve questions about the nested dictionary. But I'm still struggling with how to connect series, dictionaries, and DataFrame to more conveniently compute the sum of products.

I think this should do the trick:

result_dic = {}
for x in zip(Dict_A.items(), Dict_B.items()):
    coef = x[0][1]
    for k, v in x[1][1].items():
        if k not in result_dic:
            result_dic[k] = v*coef
        else:
            result_dic[k] += v*coef

print({key: round(result_dic[key], 3) for key in result_dic})

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