Question about += for 7. Counting in Dictionaries

What is the difference between:

    content_ratings = c_rating +1


    content_ratings[c_rating] += 1

Hi @mohula and welcome to the community!

Since the title talks about dictionaries, I will assume content_ratings is your dictionary. I will also assume that c_rating is a key in your dictionary and that it’s a string value as opposed to an int or a float value.

With these assumptions in mind, the first line (content_ratings = c_rating +1) would generate a TypeError similar to: “TypeError: Can’t convert ‘int’ object to str implicitly” while the second line (content_ratings[c_rating] += 1) would increase the value stored in content_ratings[c_rating] by 1.

The reason that the first one generates an error is because we are trying to add a string and an integer together and then assign it to a variable that we previously had assigned to a dictionary. The second one does not generate an error because it accesses one of the keys (c_rating) in the dictionary (content_ratings) and increases the integer value stored there by 1.

I’m going to go out on a limb here and guess that perhaps you wanted to know the difference between:
content_ratings[c_rating] += 1
content_ratings[c_rating] = content_ratings[c_rating] + 1

And now the difference between these two lines of code is what we call syntactic sugar and both will always produce the same result. That said, the first one is much easier to read/write and is therefore preferred over the second.

Just as an FYI, since you are new to the community, you may want to read this post about asking technical questions in the community.