dict.py
= {"cat": "meow", "dog": "woof", "horse": "neigh"}
sounds
= sounds["dog"]
dog_sound = sounds["horse"]
horse_sound
print("Dog goes", dog_sound)
print("Horse goes", horse_sound)
dict.py
= {"cat": "meow", "dog": "woof", "horse": "neigh"}
sounds
= sounds["dog"]
dog_sound = sounds["horse"]
horse_sound
print("Dog goes", dog_sound)
print("Horse goes", horse_sound)
Terminal/Command Prompt
python dict.py
Dog goes woof
Horse goes neigh
If we edit our script so that it asks for a key that doesn’t exist, we will see an error being produced:
dict.py
= {"cat": "meow", "dog": "woof", "horse": "neigh"}
sounds
= sounds["fish"]
fish_sound
print(fish_sound)
Terminal/Command Prompt
python dict.py
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~/courses/beginning_python/dict.py in <module>
2 sounds = {"cat": "meow", "dog": "woof", "horse": "neigh"}
3
----> 4 fish_sound = sounds["fish"]
5
6 print(fish_sound)
KeyError: 'fish'