Key error when looping a dict

Screen Link:
https://app.dataquest.io/m/314/dictionaries-and-frequency-tables/11/keeping-the-dictionaries-separate

My Code:
content_ratings = {‘4+’: 4433, ‘12+’: 1155, ‘9+’: 987, ‘17+’: 622}
total_number_of_apps = 7197

c_ratings_proportions = {}
c_ratings_percentages = {}
for key in content_ratings:
proportion = content_ratings[key] / total_number_of_apps
percentage = proportion * 100

percentage = c_ratings_proportions[key] 
percentage = c_ratings_percentages[key] 

print(c_ratings_proportions)
print(c_ratings_percentages)


Hi, the following error message comes up, can someone tell me why is that? 
but when I switch the " = (assign) " position, the codes can be run successfully. why is that? 
c_ratings_proportions[key] = proportion 
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)
<ipython-input-1-2ff6ebbab910> in <module>
      8     percentage = proportion * 100
      9 
---> 10     proportions = c_ratings_proportions[key]
     11     percentage = c_ratings_percentages[key]
     12 

KeyError: '4+'

Hi @samantha,

Welcome to the Community!

The issue is with your assigning the values to the keys in the dictionaries. It should be just the opposite::

c_ratings_proportions[key] = proportion
c_ratings_percentages[key] = percentage

Hi and welcome to the community!

The assignment order matters. If you say percentage = c_ratings_proportions[key], the computer interprets it as 'assign to the variable percentage the value that corresponds to c_ratings_proportions[key]. In the first iteration the dictionary c_ratings_proprotion is still empty at the moment when c_ratings_proportions[key] is called. That´s why you get the error that there´s no key '4+' in the dictionary.

Nevertheless if you want to assign values to the dictionary (using the order c_ratings_proportions[key] = proportion ), it doesn´t matter if the dictionary is empty or not. If there´s no key, let´s say, '4+' in the dictionary yet, it´ll be created and a value assigned to it. And if the key already exists, a new value will be assigned to it.

1 Like