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

0 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)
Run Code Online (Sandbox Code Playgroud)

Tom*_*ton 6

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

尝试/除外:

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

使用dict的get方法:

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