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

MRAB python at mrabarnett.plus.com
Sat Aug 18 20:01:31 EDT 2018


On 2018-08-19 00:16, giannis.dafnomilis at gmail.com wrote:
> I have the results of an optimization run in the form found in the following pic: https://i.stack.imgur.com/pIA7i.jpg.
> 
> How can I multiply the dictionary values of the keys FEq_(i,_j,_k,_l) with preexisting values of the form A[i,j,k,l]?
> 
> For example I want the value of key 'FEq_(0,_0,_2,_2)' multiplied with A[0,0,2,2], the value of key 'FEq_(0,_0,_4,_1)' multiplied with A[0,0,4,1] etc. for all the keys present in my specific dictionary.
> 
> I have been trying to correspondingly multiply the dictionary values in the form of
>      varsdict["FEq_({0},_{1},_{2},_{3})".format(i,j,k,l)]
> 
> but this is not working as the indexes do not iterate consequently over all their initial range values, they are the results of the optimization so some elements are missing. I also could not find something of a similar nature where I looked.
> 
> Thank you for the help!
> 
Iterate over the keys in varsdict and, for each key, extract the indexes.

With an example:

 >>> key = 'FEq_(0,_0,_2,_2)'
 >>> key
'FEq_(0,_0,_2,_2)'
 >>> key.split('(')[1]
'0,_0,_2,_2)'
 >>> key.split('(')[1].split(')')[0]
'0,_0,_2,_2'
 >>> key.split('(')[1].split(')')[0].split(',_')
['0', '0', '2', '2']

Now convert them to ints and assign to variables:

 >>> i, j, k, l = map(int, key.split('(')[1].split(')')[0].split(',_'))

Now you can get A[i,j,k,l].



More information about the Python-list mailing list