简体   繁体   中英

How to count the unique values of a column and append each value to a dictionary?

The tutorial suggests this solution

opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)
content_ratings = {}
for row in apps_data[1:]:
    c_rating = row[10] #the content rating that says which app is suitable for which age
    if c_rating in content_ratings:
        content_ratings[c_rating] += 1
    else:
        content_ratings[c_rating] = 1
print(content_ratings) 

The output is

{'17+': 622, '4+': 4433, '9+': 987, '12+': 1155}

I just want to understand the code logic. The line says if c_rating in content_ratings: is supposed to return False as it doesn't meet the condition since the content_rating itself is empty so c_rating is not in the dictionary. How does this logic find the content rating and append it to the dictionary?

Both lines in if-else statement looks same, but there is slight difference, + sign:

if c_rating in content_ratings:
    content_ratings[c_rating] += 1
else:
    content_ratings[c_rating] = 1

content_ratings[c_rating] = 1 this is how an element is added into dictionary in python. Also you can update existed element dictionary in same way; here content_ratings[c_rating] += 1 you get the existing element and increase its value.

So, you are right, when if c_rating in content_ratings: returns false , it adds elements, otherwise, it updates its value (increasing count).

You can see basic operation on dictionary in docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM