在字典中查找关键字,并打印关键字及其值

2024-10-04 03:17:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力在歌曲词典中寻找那把钥匙。它们是歌曲的标题,值是歌曲的长度。我想在字典里搜索这首歌,然后打印出那首歌和它的时间。我已经想出了寻找这首歌的办法,但也记不起如何发挥它的价值。这是我目前拥有的。你知道吗

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

Tags: in标题字典songdef时间keys歌曲
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

不需要遍历字典键-快速查找是使用字典而不是元组或列表的主要原因之一。你知道吗

用try/except:

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

相关问题 更多 >