Act fast, special offers end soon! Up to $294 is savings when you get Premium today.
Get offer codes

How can a variable check through an empty dictionary

Screen Link: Learn data science with Python and R projects

My Code:

ratings = ['4+', '4+', '4+', '9+', '9+', '12+', '17+']

for c_rating in ratings:
    if c_rating in content_ratings:
        content_ratings[c_rating] += 1
    else:
        content_ratings[c_rating] = 1
    print(content_ratings)

print('Final dictionary:')
print(content_ratings)
Replace this line with your code

What I expected to happen:
This is where my confusion lies: as a beginner python coder, i want to know how the variable c-rating under the if statement can check through an empty dictionary and if it exists, then increment same key value by 1

What actually happened:

Replace this line with the output/error
1 Like

The dictionary is empty but that doesn’t mean it does not exist. It is still possible to check whether or not an item is present inside that dictionary.

The if condition checks whether c_rating is a key in the dictionary or not. And if the dictionary is empty, that means that key is not present in that dictionary. And if it’s not present in the dictionary, the code adds that key to the dictionary and sets a value of 1 for that key. Let me know if that clears the confusion or not.

1 Like

I understand the explanation but consider this “if c_rating in content_ratings:” i presume this means, if the iteration variable “c_ratings” exist in content_ratings? if this is true do “content_ratings[c_rating] += 1”. i tried to figure out the code and i noticed if the iteration variable goes into the empty dictionary and where it finds the key example “4+”, it increments the value by “1”. How does it find the key in an empty dictionary to increment same?

1 Like

This isn’t contained in my lectures. Should i assume this is what happens even if the “if statement” is True?..that it adds the key “4+” to the empty dictionary where the key doesn’t exist?

Are you sure? For the Mission corresponding to the link you shared, the 4th Mission Step - Alternative Method of Creating a Dictionary covers this concept -

Adding a value to a dictionary follows the pattern dictionary_name[index] = value. To add a value 4433 with an index '4+' to a dictionary named content_ratings, we need to use the code content_ratings['4+'] = 4433.

content_ratings = {}
content_ratings['4+'] = 4433

No, this is what happens when the if condition is not True. The condition is -

if c_rating in content_ratings:

The above being True would mean that c_rating is a key in content_ratings.

When the above is not True, that’s when the else part of the condition triggers and creates the key and assigns it a value.

If it’s True, that means the key already exists in the dictionary, and the corresponding value is increased by 1.

1 Like

I expect the “else” to be triggered as nothing exists in the dictionary.

I understand this perfectly. My grouse is the if statement which i expect that if true, would trigger a condition…

Exactly my thoughts!..but c_rating is non-existent in the empty dictionary. How does it add the value corresponding to the key or increment the “key”…

Since the dictionary is empty at that point, then the if condition returns a False. And when it’s False, the code after the else condition runs -

content_ratings[c_rating] = 1

The above code runs and the key is then added to the dictionary and is assigned the value 1.

Work through a very small example -

ratings = ["4+", "4+"]

content_ratings = {}

Now look at the loop

for c_rating in ratings:

At the first iteration, what would c_rating be? It would be "4+".

Then we have the if condition -

if c_rating in content_ratings:

Is the above True? No. Because content_ratings is empty at this point.

So, the else statement code will run -

else:
        content_ratings[c_rating] = 1

After the above code runs, the dictionary would have the following content -

content_ratings = {"4+": 1}

Now, we come to the 2nd iteration of the loop. c_rating is "4+" now. We check the if condition -

if c_rating in content_ratings:

Is the above True? Yes. Because after the previous iteration content_ratings has the key "4+" inside of it.

So, the following code runs -

content_ratings[c_rating] += 1

The above code runs and it adds a 1 to the value for that key. So, the dictionary would now be -

content_ratings = {"4+": 2}

Does that help?

2 Likes

Thanks much for this explanation. I am unclear however about how the else statement works after the second time +1 is added for “4+“ and “4+”. So to reiterate:

After reaching content_ratings = {“4+”: 2}, the code loops one more time, and finds that there is no more “4+”. What does the interpreter do then? Does it:

  1. Skip “4+” and move on to “9+”?
  2. Or look for “4+“, fails to find a value, and runs the code for “else” (i.e. content_ratings[c_rating]=1)?

I believe that it does Process 1 right? That’s why “4+” key remains at value 2 and the interpreter then adds the value for “9+”

Is my interpretation of what is going on correct?

We have

If

content_ratings = {“4+”: 2}

then that means that we have only iterated twice. The first iteration set the value for '4+' to be 1. The second iteration updated the value for '4+' to a 2.

There is still one more '4+' left.

thanks for the quick reply, much appreciated. But now that the interpreter has counted three “4+”, and there is no more “4+” left what does it do then?

  1. Skip “4+” and move on to “9+”?
  2. Or look for “4+“, fails to find a value, and runs the code for “else” (i.e. content_ratings[c_rating]=1)?

i think it will function like Process 1 because that’s how it works eventually (since if it functions like Process 2, it will incorrectly count “4+” as one instead of three.

But why does it work that way? logically speaking, as someone who is relatively new to Python and isn’t too hung up over structure, I can see it work like Process 2 and return an incorrect count of one, in which case the proper way to write the code should be to totally ignore having an Else statement in the first place, and just stop it at the If statement (because logically, if the interpreter sees that the list does not have any more “4+” it should stop counting it and move on to the next key “9+”). However I have played around with this alternative and the result is an error instead.

I guess you always say “because that’s the way Python is”, if there is no explanation possible :slight_smile:

ok after some reflection, i think the interpretation is:
List of ratings = {“4+”, “4+”, ”4+”, ”9+”, ”9+”, ”12+”, ”17+”}

So how it works is:
Interpreter looks up to check if a key “4+” exists in the dictionary (False so set value at 1)
then looks up “4+” (True so set value by +1 (running total is now 2),
then looks up “4+” (True so set value at +1 (running total is now 3),
then looks up “9+” (False so set value at 1),
then looks up “9+” (True so set value at +1 (running total is now 2),
then looks up “12+“ (False so set value at 1),
then finally looks up “17+” (False so set value at 1),
and at this point, there is no more value in the list, so the interpreter stops.

This is correct?

2 Likes

Yup, that’s correct!

1 Like

Nice….thanks!

I’m still new to this but I hope I will get there eventually :grinning:

1 Like

I was struggling to understand this concept as well. The above provided clarity. Thank you and to those who commented to make this clear.