Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字典中搜索关键字,并打印关键字及其值_Python_Search_Dictionary_Key - Fatal编程技术网

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

Python 在字典中搜索关键字,并打印关键字及其值,python,search,dictionary,key,Python,Search,Dictionary,Key,我正试图在《歌曲词典》中查找这把钥匙。这些键是歌曲标题,值是歌曲的长度。我想在字典里搜索这首歌,然后打印出那首歌和它的时间。我已经找到了寻找这首歌的方法,但也记不起如何发掘它的价值。这是我目前拥有的 def getSongTime(songDictionary): requestedSong=input("Enter song from playlist: ") for song in list(songDictionary.keys()): if request

我正试图在《歌曲词典》中查找这把钥匙。这些键是歌曲标题,值是歌曲的长度。我想在字典里搜索这首歌,然后打印出那首歌和它的时间。我已经找到了寻找这首歌的方法,但也记不起如何发掘它的价值。这是我目前拥有的

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

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

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

我认为使用try-catch不适合此任务。只需在

requestedSong=input("Enter song from playlist: ")
if requestedSong in songDictionary:
    print songDictionary[requestedSong]
else:
    print 'song not found'
我强烈建议你阅读这篇文章
也可以查看以下问题: