Austin Eiter
Austin Eiter

Reputation: 3

Searching for key in dictionary, and printing the key and its value

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)

Upvotes: 0

Views: 237

Answers (2)

Saeid
Saeid

Reputation: 4265

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

Upvotes: 2

Tom Dalton
Tom Dalton

Reputation: 6190

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"))

Upvotes: 6

Related Questions