How to multiply dictionary values with other values based on the dictionary's key?

giannis.dafnomilis at gmail.com giannis.dafnomilis at gmail.com
Sun Aug 19 08:29:46 EDT 2018


On Sunday, August 19, 2018 at 1:42:29 PM UTC+2, Steven D'Aprano wrote:
> On Sun, 19 Aug 2018 03:15:32 -0700, giannis.dafnomilis wrote:
> 
> > Thank you MRAB!
> > 
> > Now I can get the corresponding dictionary value A[i,j,k,l] for each key
> > in the varsdict dictionary.
> > 
> > However how would I go about multiplying the value of each
> > FEq_(i,_j,_k,_l) key with the A[i,j,k,l] one? Do you have any insight in
> > that?
> 
> Do you want to modify the varsdict values in place?
> 
> varsdict['Feq_(i,_j,_k,_l)'] *= A[i,j,k,l]
> 
> which is a short-cut for this slightly longer version:
> 
> temp = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l]
> varsdict['Feq_(i,_j,_k,_l)'] = temp
> 
> 
> 
> If you want to leave the original in place and do something else with the 
> result:
> 
> result = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l]
> print(result)
> 



> Do you want to modify the varsdict values in place? 
> 
> varsdict['Feq_(i,_j,_k,_l)'] *= A[i,j,k,l] 
> 
> which is a short-cut for this slightly longer version: 
> 
> temp = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l] 
> varsdict['Feq_(i,_j,_k,_l)'] = temp 
> 
> 
> 
> If you want to leave the original in place and do something else with the 
> result: 
> 
> result = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l] 
> print(result) 
> 

Thanks again for your answers Steven. I will try to explain it simpler because I think I tend to complicate things. 

With your help I have arrived at this point: 
I have the dictionary varsdict (size 5) as below 
Key                        Type        Size     Value 
FEq_(0,_0,_0,_0)           float        1        1.0 
FEq_(0,_0,_1,_1)           float        1        1.0 
FEq_(0,_0,_2,_2)           float        1        1.0 
FEq_(0,_0,_3,_0)           float        1        1.0 
FEq_(0,_0,_4,_1)           float        1        1.0 

and the dictionary B (size 150) as below 
Key                        Type        Size     Value 
FEq_(0,_0,_0,_0)           float        1        1500.0 
FEq_(0,_0,_0,_1)           int          1        0 
... 
FEq_(0,_0,_1,_1)           float        1        3300.0
... 
FEq_(0,_0,_2,_2)           float        1        2200.0
...
FEq_(0,_0,_4,_1)           float        1        4000.0

for dictionary B the i,j,k,l ranges run as far as my input ranges when I started the model. So now I only want to multiply the values with the same keys with each other and get the sum of it.

result = Sum(varsdict['FEq_(i,_j,_k,_l)']*B['FEq_(i,_j,_k,_l)']

As I mentioned above I have been trying this with 
{k : v * B[k] for k, v in varsdict.items() if k in B} 

or 

for key in varsdict: 
    if key in B: 
        print(int(varsdict[key]) * int(B[key])) 

but all I get is an empty dictionary. 



More information about the Python-list mailing list