Dict question, confusion about for loop

Screen Link:
(Learn data science with Python and R projects)

hi all,

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)     
    c_ratings_proportions[key] = proportion
    percentage = proportion * 100 
    c_ratings_percentages[key] = percentage #for each element in c_ratings_percentages
    

could someone please explain to me what content_ratings[key] is doing?

and what about c_ratings_proportions[key] ?

is this taking each element in content_ratings and iterating over it?

so for here:

proportion = (content_ratings[key] / total_number_of_apps)     
    c_ratings_proportions[key] = proportion

is this taking every element and applying the same calculation?

thanks :slight_smile:
-your python nub

Hi @saturdaynightwrist ,

content_ratings[key] access the value in each key in the dictionary.

If you run this:

for key in content_ratings:
    print(key)

You’ll see this output:

4+
12+
9+
17+

This means you’re looping through the keys as I said.

If you run this:

for key in content_ratings:
    print(content_ratings[key])

You’ll see this output:

4433
1155
987
622

These are the values stored in each key which content_ratings[key] is accessing.


and what about c_ratings_proportions[key] ?

The c_ratings_proportions is empty, so the code below creates a new key and store some new value to this key in this dict:

c_ratings_proportions[key] = proportion

is this taking each element in content_ratings and iterating over it?

It’s not iterating over each element in content_ratings , it 's iterating over content_ratings itself and accessing each of its elements.


is this taking every element and applying the same calculation?

Exactly! It takes every element, applies the same calculation, and then stores it in the c_ratings_proportions dictionary.


I hope this helps you.

1 Like

thank you very much for your detailed response :slight_smile: it has indeed helped me understand

1 Like