Iterate through a list inside a dictionary in python

Viewed 15737

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:

dic = {"A":[2,4,6,8], "B":[4,6,8,10]}

desired output:

dic2 = {"A":[1,2,3,4], "B":[2,3,4,5]}

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:

def divide(dic):
    dic2 = {}
    for i in range(len(dic)):
        for j in range(len(dic[i])):
            dic2[i][j] = dic[i][j]/2
    return dic2

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

7 Answers

I used a subtle variation of Wim's answer above (focus is on the comprehension using key):

dic = {"A":[2,4,6,8], "B":[4,6,8,10]}
dic2 = {k:[v/2 for v in dic[k]] for k in dic.keys()}

to get:

dic2
{'A': [1.0, 2.0, 3.0, 4.0], 'B': [2.0, 3.0, 4.0, 5.0]}
Related