Home > Back-end >  How to replace values of elements in a list with the values of multiple dictionaries?
How to replace values of elements in a list with the values of multiple dictionaries?

Time:01-12

I have produced a list_1 consisting of elements with three values. These elements represent certain configurations of machinery. To derive the power consumption for each element I want to create a list_2 of elements in which the values pf list_1 are replaced by the values from related dictionaries. How can I accomplish this?

This is a simplified example of the problem. This is the list I created:

a = range(2,10)
b = range (12)
c = range(13)

list_1 = []
list_1 = [list(i) for i in product(a,b,c)]
list_1 = [item for item in list_1 if not (item[1] > item[0] or (item[1] and item[2] > 0) or (item[0]   item[2] > 10))]
list_1

And then the dictionaries would look something like this:

dict_a = { 2:25, 3:30, 4:35, 5:40, 6:45, 7:50, 8:55, 9:60}
dict_b = { 0:15, 1:25, 2:35, 3:40, 4:45, 5:50, 6:55, 7:60, 8:75, 9:80, 10:85, 11:90 }
dict_c = { 0:15, 1:25, 2:35, 3:40, 4:45, 5:50, 6:60, 7:70, 8:75, 9:80, 10:95, 11:100, 12:110 }

So, I want to replace the three values of the elements in list_1 with the corresponding values from the key:value pairs in the dictionaries.

Many thanks in advance for your response!

CodePudding user response:

item in your comprehension is a list that we can unpack and rebuild based on your dictionaries.

import itertools

a = range(2,10)
b = range (12)
c = range(13)

dict_a = { 2:25, 3:30, 4:35, 5:40, 6:45, 7:50, 8:55, 9:60}
dict_b = { 0:15, 1:25, 2:35, 3:40, 4:45, 5:50, 6:55, 7:60, 8:75, 9:80, 10:85, 11:90 }
dict_c = { 0:15, 1:25, 2:35, 3:40, 4:45, 5:50, 6:60, 7:70, 8:75, 9:80, 10:95, 11:100, 12:110 }

list_1 = [
    [dict_a[i[0]], dict_b[i[1]], dict_c[i[2]]]
    for i
    in itertools.product(a,b,c)
    if not (i[1] > i[0] or (i[1] and i[2] > 0) or (i[0]   i[2] > 10))
]
  • Related