Home > Mobile >  How to iterate a list of dictionaries and perform elementwise calculations with entries
How to iterate a list of dictionaries and perform elementwise calculations with entries

Time:07-15

I am trying to multiply entries of a list of dictionaries, see the example code below.

It generates TypeError: list indices must be integers or slices, not dict

How can this kind of operation be achieved?

list_of_uscases = [

{
"uscase": 1,
"power": 400,
"time": 2,
"energy_consumed": 0,
},

{ 
"uscase": 2,
"power": 500,
"time": 2,
"energy_consumed": 0, 
},

{
"uscase": 3,
"power": 700,
"time": 2,
"energy_consumed": 0, 
}
]

for n in list_of_uscases:
  list_of_uscases[n]["energy_consumed"]= (list_of_uscases[n]["power"]* list_of_uscases[n]["time"])
  print(list_of_uscases[n]["energy_consumed"])

CodePudding user response:

You can simply loop over the list and modify each dictionary.

for d in list_of_uscases:
    d["energy_consumed"]  = d["power"] * d["time"]
    print(d["energy_consumed"])
# 800
# 1000
# 1400
  • Related