-1

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"])

MacUserXL
  • 35
  • 5
  • 3
    ```for n in list_of_uscases``` already "puts" ```list_of_uscases[X]``` in n => All you need to do is ```n["energy_consumed"] = ...``` – Metapod Jul 12 '22 at 16:02
  • Yes, this is very comfortable in Python. You don't need the index. You get the entries one by one. This is often what you need. Sometimes you need the index. Then you can use `for n in range(len(list_of_usecases)):`. Sometimes you need the index and the elements. Then you can use `for n, i in enumerate(list_of_usecases):` Sometimes you need an index, but you have no data structure that uses numbers as an index (e.g. line numbers when reading a file). Then you can use `for n,i zip(range(len(list_of_usecases)), list_of_usecases):`. These example are the most used loops, so you should know them. – habrewning Jul 12 '22 at 16:19
  • @habrewning For your last example, i highly recommend to use ```enumerate()```, which will concatenate the index and the value: ```for index, val in enumerate(my_iterable):``` – Metapod Jul 13 '22 at 12:53
  • @Metapod Yes, this would also for me the prefered way. But this does not work in case my_iterable is a generator. – habrewning Jul 13 '22 at 15:31

1 Answers1

0

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
cottontail
  • 10,268
  • 18
  • 50
  • 51