10. Looping Over Dictionaries

The example included in the lesson shows:

print(iteration_variable) returns a list of keys (17+, 12+, etc…)

print(content_ratings[iteration_variable]) returns a list of values (4433, 987, etc…)

Why does the same variable return different results depending on where it is placed in the print request?

Thanks

1 Like

Hello @jrwainwright, welcome to the community!

I believe you are talking about lessons on Dictionaries and Frequency Tables.

When we iterate over a dictionary with a for loop, the looping is done by default over the dictionary keys:
so when you run this block of code:

content_ratings = {'4+': 4433, '12+': 1155, '9+': 987, '17+': 622}
for iteration_variable in content_ratings:
    print(iteration_variable)

This prints out all the keys in the dictionary and gives an output:
12+ 9+ 4+ 17+

In this case, the variable iteration_variable represents the keys in the dictionary.

I hope this helps.

2 Likes

@jrwainwright.

For the second line of code print(content_ratings[iteration_variable]) as in this code block:

content_ratings = {'4+': 4433, '12+': 1155, '9+': 987, '17+': 622}
for iteration_variable in content_ratings:
    print(content_ratings[iteration_variable])

In this case, the variable iteration_variable still represents the keys in the dictionary but it is used to access the dictionary values; following the general format for accessing values in a dictionary dictionary_name[key]. Therefore we use content_ratings[iteration_variable]

Hence, print(content_ratings[iteration_variable]) returns all the values of the keys in the dictionary giving an output of 1155 987 4433 622.

I hope this answers your question.

3 Likes

@doyinsolamiolaoye

Yes this really helps. I thought it might be the case but I didn’t want to move forward on an assumption.

Your response makes it crystal clear. Thanks!!

3 Likes

@jrwainwright,

You’re welcome! If it solved your problem, would you mind marking the answer as solution? Thank you!

Hey buddy! Hope you are alright. Dataquest gives some benefits to the really hardworking people in the community who take time out of their day to help with answering some of our questions. I’m also on the same lesson and found this helpful. If you find the time out of your day, mark doyinsolamiolaoye’s comment as the solution :slight_smile:

P.S. I do not know the generous person who answered the question. Just looking out for us all as a community :slight_smile: Also, thanks for asking the question! It was helpful for me as well!

@MohammedElnaiem,

I am glad you found my reply helpful and thanks for looking out for us all in the community. It’s always good to help.

Good luck and Happy Learning!