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:

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.

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:

def divide_dic(dic):
    dic2 = {}

    # Iterate through the dictionary based on keys.
    for dic_iter in dic:

        # Create a copy of the dictionary list divided by 2.
        list_values = [ (x / 2) for x in  dic[dic_iter] ]

        # Add the dictionary entry to the new dictionary.
        dic2.update( {dic_iter : list_values} )

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