[英]Searching for key in dictionary, and printing the key and its value
我正在嘗試在歌曲字典中搜索鍵。 它們的鍵是歌曲標題,而值是歌曲的長度。 我想在字典中搜索歌曲,然后打印出該歌曲及其時間。 我已經想出了尋找這首歌的方法,但是想不起來如何發揮它的價值。 這是我目前擁有的。
def getSongTime(songDictionary):
requestedSong=input("Enter song from playlist: ")
for song in list(songDictionary.keys()):
if requestedSong in songDictionary.keys():
print(requestedSong,value)
無需遍歷字典鍵-快速查找是使用字典而不是元組或列表的主要原因之一。
嘗試/除外:
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不適合完成此任務。 只需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
也要檢查一下這個問題: 檢查字典中是否存在給定的鍵
嘗試vs如果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.