Reputation: 111
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?
Upvotes: 1
Views: 82
Reputation: 2169
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.
Upvotes: 2