Skip to content
Advertisement

Iterate through a list inside a dictionary in python

I’m very new to Python and I need to create a function that divides by 2 the values in the lists inside the dictionary:

JavaScript

desired output:

JavaScript

I found this post

python: iterating through a dictionary with list values

which helped a little, but unfortunately is the “whatever” part of the example code that I can’t figure out.

I tried this:

JavaScript

I wrote different variations, but I keep getting a KeyError: 0 in the “for j…” line.

Advertisement

Answer

You have to access elements of the dictionary using their key. In the example keys are ‘A’ and ‘B’. You are trying to access the dictionary using an integer and that gives you the range error.

The following function works:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement