在字典中搜索键,并打印键及其值

时间:2015-11-22 23:40:02

标签: python search dictionary key

我正在尝试在歌词典中搜索关键字。它们的键是歌曲标题,值是歌曲的长度。我想在字典中搜索这首歌,然后打印出那首歌和它的时间。我已经想出要搜索这首歌,但不记得如何发挥它的价值。这是我现在拥有的。

def getSongTime(songDictionary):
    requestedSong=input("Enter song from playlist: ")
    for song in list(songDictionary.keys()):
        if requestedSong in songDictionary.keys():
            print(requestedSong,value)

2 个答案:

答案 0 :(得分:6)

没有必要遍历字典键 - 快速查找是使用字典而不是元组或列表的主要原因之一。

尝试/除外:

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

使用dict的get方法:

def getSongTime(songDictionary):
    requestedSong=input("Enter song from playlist: ")
    print(requestedSong, songDictionary.get(requestedSong, "Not found"))

答案 1 :(得分:2)

我不认为使用try catch对此任务有好处。只需使用运算符in

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

我强烈建议您阅读本文 http://www.tutorialspoint.com/python/python_dictionary.htm
另请查看这些问题: check if a given key exists in dictionary
try vs if