Why does key print the value?

Question

Why does key print the value?

Answer

We are using key as exactly that - the current key name that our loop is on. Recall that when we write dictionary_name[key_name], it provides us with the value stored under that key name in that dictionary. So that’s exactly what we accomplish by writing print dictionary[key] inside of our for loop!

5 Likes

What would be the method to actually have it print the key if that was what you wanted?

3 Likes

Hi @ryan.hurley.btc ,

Copy and execute the following demo …

# executed using Python 3.7.0

# create a dictionary of scrabble scores for each letter
scrabble = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, 
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, 
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, 
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, 
         "x": 8, "z": 10}

key = "m"
# print the value accociated with key
print(scrabble[key])
# display key
print(key)
# print all the keys, unsorted
print(list(scrabble.keys()))
# print all the keys and their associated values, unsorted
print("\nunsorted")
for key, value in scrabble.items():
    print(key, value)
# print all the keys and their associated values, sorted by key
print("\nsorted")
for key, value in sorted(scrabble.items()):
    print(key, value)

Note in the above that if key refers to the key, then the following will display that key …

print(key)
11 Likes

Realized I never responded here. Thanks for the reply, this helped.

1 Like

Note that dictionaries are unordered , meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order.

I don’t understand the above statement. I did the for loop 3 times and get the same pattern of order.
Is there really no pattern there, and the result will be randomized?

I think the point was that dictionaries are not automatically sorted rather than being actively randomised. Order is generally consistent but it’s not guaranteed so you shouldn’t rely on it.

* Since 3.7 the language now specifies that dictionaries are ordered (insertion order)- Built-in Types — Python 3.9.1 documentation

2 Likes

Found a smaller solution for printing the KEY and Value

for i,j in webster.items():
print(str(i)+': ’ + str(j))