简体   繁体   中英

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM