Functions: Fundamentals screen 10

Screen Link:
https://app.dataquest.io/m/315/functions%3A-fundamentals/10/keyword-and-positional-arguments

My Code:
def freq_table(data_set, index):
frequency_table = {}

for row in data_set[1:]:
    value = row[index]
    if value in frequency_table:
        frequency_table[value] += 1
    else: 
        frequency_table[value] = 1
        
    return frequency_table

content_ratings_ft = freq_table(apps_data, 10)
ratings_ft = freq_table(data_set=apps_data, index=7)
genres_ft = freq_table(index=11, data_set=apps_data)

Replace this line with your code

What I expected to happen:

What actually happened:
content_ratings_ftdict (<class β€˜dict’>)

  • actual + expected

  • {β€˜4+’: 1}

  • {β€˜4+’: 4433, β€˜12+’: 1155, β€˜9+’: 987, β€˜17+’: 622}
Replace this line with the output/error

It has happened several times to me. I do not exactly know what is wrong. Whenever I check my answer to the solution they are the same but the output is always shorter than expected.
Thanks in advance for your help.

Hi @maungkhantdelica:

I see the issue here. It is intended to create a dictionary with the values sown below.

Going through the code logically, after the first iteration of the loop, the dictionary, containing the first category '4+', and a count of 1 (since the category did not exist before the loop began) and thereafter the return statement is reached and this key value pair is immediately removed. To resolve this, put the return statement outside the for loop.

Indentation does matter in Python.

Try to understand what your code is doing with the test data provided in the csv view in future and I’m sure this will allow you to better understand your bug and solve it more efficiently.

Solution
def freq_table(data_set, index):
    frequency_table = {}
    
    for row in data_set[1:]:
        value = row[index]
        if value in frequency_table:
            frequency_table[value] += 1
        else:
            frequency_table[value] = 1
        
    return frequency_table
content_ratings_ft = freq_table(apps_data,10)
ratings_ft = freq_table(apps_data,7)
genres_ft = freq_table(apps_data,11)
1 Like

Thanks a lot. Really helped me go forward. I understand the importance of indentation. But I was not aware that could cause a problem.