Python Dictionaries & Frequency Tables

ratings = [‘4+’, ‘4+’, ‘4+’, ‘9+’, ‘12+’, ‘12+’, ‘17+’, ‘17+’]

content_ratings = {}

for i in ratings:
    if i in content_ratings:
        content_ratings[i] += 1
    else:
        content_ratings[i] = 1
        
print(content_ratings)   

Why do we need else statement in this particular case? The code is simple, yet I do not understand what is the role of content_ratings[i] = 1.

I would be happy, if someone could explain.

Hi Luka, welcome to our community!

In the mission we are building a dictionary content_ratings that will contain the different ratings and how many times each rating occurs within the ratings list. When you go through the first iteration, the dictionary is empty, so when it searches for the key ‘4+’, it won’t be found. Then it goes to the else statement, where it adds the key and gives it a count of 1 into the dictionary. On the next iteration, since ‘4+’ already exists as a key, it will just process the if-statment to add 1 to the ‘4+’ key in the dictionary. Every time the loop encounters a rating that doesn’t already exist, it will be added to the dictionary by the else statement.

I hope that clears things up!

1 Like

Thank you April for a clear and precise explanation :cowboy_hat_face: