3/18 The 'in' Operator (expected behaviour)


#1

How does line 8 (last line) in the following code output the value instead of the key? I would have expected it to output the key but instead it prints the key’s value.

my_dict = {
  "Rank": "Novice",
  "Language": "Python",
  "Version": 2.7
}

for key in my_dict:
  print key, my_dict[key]

#2

it should print both? key should print the key, while my_dict[key] should print the value, given you use the key to retrieve value from my_dict


#3

My bad. I phrased it wrong. It does print both. But how does it print the value at all? I understand print key prints the key, but how does my_dict[key] print the value? I would have expected it to print the key twice.


#4

doing my_dict["Rank"] gives Novice, by using the key in square brackets, you can access the value. Same with the loop, the loop assign key of dictionary to iterator (which you named key), then you can use key (iterator) to access value

how else do we access the values of dictionary? Dictionaries would be pointless if we couldn’t access value associated with key


#5

Ah, okay. I got you. Thanks.

my_dict[key] is actually my_dict["Rank"|"Language"|"Version"] as it’s iterating through the dictionary.

Thank you!


#6

yes, key is a variable which assigned the dictionary key. This might help:

example_key = "Rank"
print my_dict[example_key]

i use a variable, but given the variable contains a valid key, i can use it to retrieve a value. This is why the loop is working as well, python will assign the keys from dictionary to the loop iterator.

You print the key, as such you should be able to see that they are valid keys for dictionary?


#7

Yes, I had forgotten exactly what I was asking the program to do. In this instance, key was just a proxy for each actual dictionary key (i.e., Rank, Language, Version) as it iterated through the entire dictionary, and I was asking to retrieve the value of said key as it passed. Staring at the computer too long, I think; need a break.

Thanks, @stetim94.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.