Forums

TypeError: list indices must be integers or slices, not str

So, I’m trying to capture and store wave height data and cache it in a file based on the fetch timestamp in local time. I have hit an error with the last section.

Here is the error -

    d = sorted(data['hours'], key=lambda i: i['time'])
TypeError: list indices must be integers or slices, not str
I have tried to fix it but I have no idea how to.

Here is the full code - https://gist.githubusercontent.com/Xioto/cad6d50699d7a6599757172ab0847b93/raw/bb28c822b4df5ae1a925bc822a9204a91e57582f/main.py I apologise for all the random comments, I am a bit messy.

Here is a small exerpt from the API response to give an idea of the layout.

{"hours":[{"time":"2021-06-07T00:00:00+00:00","waveHeight":{"dwd":0.2,"fcoo":0.1,"icon":0.3,"meteo":0.09,"noaa":0.22,"sg":0.1}},{"time":"2021-06-07T01:00:00+00:00","waveHeight":{"dwd":0.19,"fcoo":0.1,"icon":0.3,"meteo":0.08,"noaa":0.2,"sg":0.1}},{"time":"2021-06-07T02:00:00+00:00","waveHeight":{"dwd":0.19,"fcoo":0.09,"icon":0.3,"meteo":0.07,"noaa":0.18,"sg":0.09}},{"time":"2021-06-07T03:00:00+00:00","waveHeight":{"dwd":0.2,"fcoo":0.09,"icon":0.3,"meteo":0.06,"noaa":0.16,"sg":0.09}},

If data is "an array of dictionaries with 'hours' and some request tracking", the error messege you get is to be expected. I'm not sure what exactly you want to be sorted, but I'd guess that you want the lists that are values of the keys "hours" in each dict to be sorted by timestamp? In such a case, it should be rather something like:

d = [{"hours": sorted(entry["hours"], key=lambda x: x["time"])} for entry in data]

Anyway, with nested structures you need to be sure you are working on the right "level".