Python Dictionaries and Frequency Tables 3/11 & 4/11

Input:
content_ratings = {‘4+’: 0, ‘9+’: 0, ‘12+’: 0, ‘17+’: 0}
ratings = [‘4+’, ‘4+’, ‘4+’, ‘9+’, ‘9+’, ‘12+’, ‘17+’]

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

Output:
{‘4+’: 1, ‘9+’: 0, ‘12+’: 0, ‘17+’: 0}
{‘4+’: 2, ‘9+’: 0, ‘12+’: 0, ‘17+’: 0}
{‘4+’: 3, ‘9+’: 0, ‘12+’: 0, ‘17+’: 0}
{‘4+’: 3, ‘9+’: 1, ‘12+’: 0, ‘17+’: 0}
{‘4+’: 3, ‘9+’: 2, ‘12+’: 0, ‘17+’: 0}
{‘4+’: 3, ‘9+’: 2, ‘12+’: 1, ‘17+’: 0}
{‘4+’: 3, ‘9+’: 2, ‘12+’: 1, ‘17+’: 1}

Input:
content_ratings = {}
ratings = [‘4+’, ‘4+’, ‘4+’, ‘9+’, ‘9+’, ‘12+’, ‘17+’]

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

Output:
{‘4+’: 1}
{‘4+’: 2}
{‘4+’: 3}
{‘4+’: 3, ‘9+’: 1}
{‘4+’: 3, ‘9+’: 2}
{‘4+’: 3, ‘9+’: 2, ‘12+’: 1}
{‘4+’: 3, ‘9+’: 2, ‘12+’: 1, ‘17+’: 1}

QUESTION:

Why do redundant values (i.e. zeros in output) appear when else is used with a filled content_ratings dictionary (first input) and redundant values do not appear when else is used with an empty content_rating dictionary (second input)?

They appear because, as you can see, in the first input, you’ve set up an initial value of 0 for every content rating in the content ratings dictionary.

In this case, there’s no initial value set in the content ratings dictionary. So, the zeros don’t appear.

Both ways work just fine.

Hi @mursuljamil,

If you feel that  your question was successfully solved, could you please mark the helpful answer as Solution? You can find here how to do it technically (in the GUIDELINE #5). Please consider this practice also for any other questions you might ask in the Community. This would be of great help both to your helpers and the other learners who can have the same questions in the future.

Many thanks and happy learning! 

:rotating_light: NOTE: This is an automated message. Please do not reply. :rotating_light:

1 Like