13. Can i use dictionary instead of a list and why it fails?)

Screen Link: Loom | Free Screen & Video Recording Software

My Code:

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

rating_count_tot={}
for row in apps_data[1:]:
    rating_number=float(row[5])
    if rating_number in rating_count_tot:
        rating_count_tot[rating_number]+=1
    else:
        rating_count_tot[rating_number]=1
print(min(rating_count_tot))
print(max(rating_count_tot))
rating_avg={"0-100k":0,"100k-500k":0,"500k":0,"500k-3kk":0}
for i in rating_count_tot:
    rating=rating_count_tot[i]
    if rating<100000:
        rating_avg["0-100k"]+=1
    elif 100000<=rating<500000:
        rating_avg["100k-500k"]+=1
    elif 500000<=rating<3000000:
        rating_avg["500k-3kk"]+=1   
print(rating_avg)

What I expected to happen:
To see at least all data counted properly.

What actually happened:
Everything went straight to first interval.

Output
0.0
2974676.0
{'0-100k': 3185, '100k-500k': 0, '500k': 0, '500k-3kk': 0}


Click here to open the screen in a new tab.
1 Like

Hi again @matro.exe,

In your dictionary rating_count_tot, app ratings are actually keys, not values (just run print(rating_count_tot) to check it). And in this line of your code:

rating=rating_count_tot[i]

you’re extracting the dictionary values, which you’ll use for further comparison. The values here represent the number of times each rating was encountered in the dataset. Hence, the majority of values will be, most probably, 1 or very low numbers anyway, since the rating values are rather unique.

Instead, what you really need here is to iterate through the dictionary keys and use exactly them for further comparison. So just remove this line from your code:

rating=rating_count_tot[i]

and compare directly the value of i (which is a dictionary’s key, i.e. a rating) at each iteration:

rating_avg={"0-100k":0,"100k-500k":0, "500k-3kk":0}
for i in rating_count_tot:
    if i<100000:
        rating_avg["0-100k"]+=1
    elif 100000<=i<500000:
        rating_avg["100k-500k"]+=1
    elif 500000<=i<3000000:
        rating_avg["500k-3kk"]+=1   
print(rating_avg)
1 Like