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'
我强烈建议你阅读这篇文章
也可以查看以下问题: