Learn
Using Dictionaries
Try/Except to Get a Key
We saw that we can avoid KeyError
s by checking if a key is in a dictionary first. Another method we could use is a try/except
:
key_to_check = "Landmark 81" try: print(building_heights[key_to_check]) except KeyError: print("That key doesn't exist!")
When we try to access a key that doesn’t exist, the program will go into the except
block and print "That key doesn't exist!"
.
Instructions
1.
Use a try
block to try to print the caffeine level of "matcha"
. If there is a KeyError
, print "Unknown Caffeine Level"
.
2.
Above the try
block, add "matcha"
to the dictionary with a value of 30
.