Counting with Dictionaries (Screen 7)

What is c_rating, what does it represent?

What is meant by the following:

for c_rating in ratings:
    if c_rating in content_ratings:
        content_ratings[c_rating] += 1

it means any value
just replace value for easy to understand
Eg:for row in data_set[1:]:
value = row[index]
if value in frequency_table:
#there is a dictionary called frequency table and it key has its value in it
frequency_table[value] += 1
else:
frequency_table[value] = 1

1 Like

@sloosh.majola, I have edited your post to include triple back ticks to format your code block.

for c_rating in ratings

Suppose ratings is a list of elements. Then c_ratings is an element within the ratings. The for loop will loop through each element in ratings and assign the value to c_ratings.

if c_rating in content_ratings:

if statement performs a check if c_ratings exists/contains in content_ratings. If c_ratings is in content_ratings, then the statement will be evaluated to True. Otherwise, False.

if c_rating in content_ratings:
        content_ratings[c_rating] += 1

The purpose of the check is to avoid having errors, since the key, value pair must be defined before incrementing.

You can improve the code using .get method

content_ratings[c_rating] = content_ratings.get(c_rating, 0) + 1  

.get returns the value of content_ratings[c_rating] if exists. Otherwise, the default value 0 is return.

Next level improvement is using defaultdict.

from collections import defaultdict
content_ratings = defaultdict(int) # default value when not found is 0

for c_rating in ratings: 
     content_ratings[c_rating] += 1

Now the code is much simpler without the unnecessary check.

1 Like