Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform operation on all "key":"value" pair in dict and store the result in a new dict object

I have a dictionary S as:

{1: [11.1, 13, 15.0], 2: [6.9, 8.5, 10.17], 3: [3.86, 4.83, 6.07], 4: [3.86, 4.83, 6.07], 5: [2.31, 2.58, 3.02]}

And an array D1_inv as:

[0.0248, 0.0296, 0.0357]

I need to obtain a product of all the items in S and D1_inv. For example, for S[1]:

[round(i*j,4) for i,j in zip(S[1],D1_inv)]
Out[282]: [0.2753, 0.3848, 0.5355]

and for S[2]:

[round(i*j,4) for i,j in zip(S[2],D1_inv)]
Out[283]: [0.1711, 0.2516, 0.3631]

Can somebody help me create a loop so that I can store all these products in a dict like S?

like image 457
IndigoChild Avatar asked Feb 20 '18 12:02

IndigoChild


1 Answers

You may use dictionary comprehension to achieve this. Within your dictionary comprehension, you need to call your list comprehension to round off the product of numbers for each list present as value in the original my_dict dictionary. It can be achieved as:

my_dict = {1: [11.1, 13, 15.0], 2: [6.9, 8.5, 10.17], 3: [3.86, 4.83, 6.07], 4: [3.86, 4.83, 6.07], 5: [2.31, 2.58, 3.02]}
d1_inv = [0.0248, 0.0296, 0.0357]

new_dict = {k: [round(i*j,4) for i, j in zip(v,d1_inv)] for k, v in my_dict.items()}

where new_dict will be a dictionary holding each key in your initial my_dict with the corresponding value as:

{1: [0.2753, 0.3848, 0.5355], 2: [0.1711, 0.2516, 0.3631], 3: [0.0957, 0.143, 0.2167], 4: [0.0957, 0.143, 0.2167], 5: [0.0573, 0.0764, 0.1078]}

Explanation: This solution comprised of:

  • an outer dictionary comprehension expression, and
  • an inner list comprehension expression.

Here, the outer dictionary comprehension:

{k: [...*list comprehension*...] for k, v in my_dict.items()}

will iterate over the dictionary pulling the tuple of ("key", "value") pairs returned by my_dict.items(). Here I am using k as a key to the new dictionary, where as value v will be used in the inner list comprehension expression:

[round(i*j,4) for i, j in zip(v,d1_inv)]

Here, zip(v,d1_inv) will return the tuple of objects corresponding to same position in d1_inv and v (from outer dictionary comprehension) , and then we are calling round() function on product of the elements present in tuple (i, j) returned by zip()'s iteration.

like image 175
Moinuddin Quadri Avatar answered Sep 19 '22 12:09

Moinuddin Quadri