Act fast, special offers end soon! Up to $294 is savings when you get Premium today.
Get offer codes

Why do you need to put empty dictionary before for loop?

Screen Link: ← Learn data science with Python and R projects

My Code:

opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)

def freq_table(column_index):
    for row in apps_data[1:]: 
        frequency_table = {}
        value = row[column_index]
        if value in frequency_table:
            frequency_table[value] += 1
        else:
            frequency_table[value] = 1
    return frequency_table        

ratings_ft = freq_table(7)

Why do I not get the full dictionary when I put the frequency_table = {} right after my for loop? Why does it need to be before the for loop?

Replace this line with the output/error

Because if it’s inside the loop then at each iteration, the dictionary will be set as empty. You initialize it outside the loop so that any changes you make to it persist as you iterate through the data.

■■■ that makes sense! thank you so much!

1 Like