u2_album = {
'title': 'The Joshua Tree',
'year': 1987,
'genre': 'Rock',
'tracks': ['Where the Streets Have No Name', 'I Still Haven\'t Found What I\'m Looking For', 'With or Without You', 'Bullet the Blue Sky', 'Running to Stand Still', 'Red Hill Mining Town', 'In God\'s Country', 'Trip Through Your Wires', 'One Tree Hill', 'Exit', 'Mothers of the Disappeared']
}
print(u2_album['title'])
print(u2_album['year'])
print(u2_album['track'])
If you try to run the above Python code, you will get a KeyError error.
The Joshua Tree
1987
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-25-be282156e277> in <cell line: 10>()
8 print(u2_album['title'])
9 print(u2_album['year'])
---> 10 print(u2_album['track'])
KeyError: 'track'
Why KeyError exception?
Python will throw a KeyError exception when a dictionary key is not found in the set of existing keys.
Fix:
If you look closely at the line where the error is thrown, we have made use of track which does not exist, its tracks.
Should be:
print(u2_album['tracks'])

Reference: https://docs.python.org/3/library/exceptions.html#KeyError
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!