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

# 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

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

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.