Help understanding output of dictionary

Hello,

I have come across the following piece of code:

fridge_contents = {“egg”:12, “milk”: 2, “apple”: 6, “celery”: 5}

for variable1, variable2 in fridge_contents.items():
if variable1 in fridge_contents:
print(fridge_contents[variable1])
if variable2 in fridge_contents:
print(fridge_contents[variable2])

Can someone explain to me why the output only consists of the values of the dictionary?
I just know it does because I checked it in Jupyter Notebook but I wonder why
My initial guess was that it would output both keys and values

Thanks!
Lora

Hi
So, you’re looping through all the items in the dictionary.
For each loop,
variable1 holds the key
variable2 has the value

for variable1, variable2 in fridge_contents.items():

Now,

if key in dict:

is true when x is a key in the dictionary
So, for this if statement;

if variable1 in fridge_contents:
print(fridge_contents[variable1])

It asks if variable1 is a key in the dictionary. When it finds it, the next line prints the value associated with that key.
This means, in your example, it’d would print out the numbers as you found.
For the next bit, though,

if variable2 in fridge_contents:
print(fridge_contents[variable2])

variable2 are the values, but the if statement thinks it’s looking for keys. So, it obviously can’t find them, the if condition is false and it doesn’t go to the print statement.
(Incidentally, the print statement would also assume variable2 is a key, so if it tried to run that line it would throw an error when it couldn’t find it in the dictionary).

To print both keys and values you could do this (I changed the names to key, value just to make it a little clearer, variable1, variable2 would work just as well);

for key, value in fridge_contents.items(): 
  print(key)
  print(value)

alternatively, you could loop through just the keys

for key in fridge_contents.keys():
  print(key)
  print(fridge_contents[key])

Hope that helps

1 Like

What is a dictionary? Start with that; and, be sure where you’re going from there.

Thanks for this! As I read your explanation, it sort of makes sense but still I find it rather convoluted to be honest
Hopefully as I progress, I will see it differently