0

I am trying to search for the key in the dictionary of songs. They keys are the song titles, and the value is the length of the song. I want to search for the song in the dictionary, and then print out that song and its time. I have figured out searching for the song, but can't remember how to bring out its value as well. Here is what I currently have.

def getSongTime(songDictionary):
    requestedSong=input("Enter song from playlist: ")
    for song in list(songDictionary.keys()):
        if requestedSong in songDictionary.keys():
            print(requestedSong,value)
Totem
  • 7,189
  • 5
  • 39
  • 66
Austin Eiter
  • 3
  • 1
  • 2

2 Answers2

6

There'no need to iterate through the dictionary keys - quick lookup is one of the main reasons for using a dictionary instead of a tuple or list.

With a try/except:

def getSongTime(songDictionary):
    requestedSong=input("Enter song from playlist: ")
    try:
        print(requestedSong, songDictionary[requestedSong])
    except KeyError:
        print("Not found")

With the dict's get method:

def getSongTime(songDictionary):
    requestedSong=input("Enter song from playlist: ")
    print(requestedSong, songDictionary.get(requestedSong, "Not found"))
Tom Dalton
  • 6,122
  • 24
  • 35
2

I don't think using try catch is good for this task. Simply use the operator in

requestedSong=input("Enter song from playlist: ")
if requestedSong in songDictionary:
    print songDictionary[requestedSong]
else:
    print 'song not found'

And I strongly recommend you to read this article http://www.tutorialspoint.com/python/python_dictionary.htm
Also check out this questions too: check if a given key exists in dictionary
try vs if

Community
  • 1
  • 1
Saeid
  • 4,147
  • 7
  • 27
  • 43