简体   繁体   English

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

[英]Searching for key in dictionary, and printing the key and its value

I am trying to search for the key in the dictionary of songs. 我正在尝试在歌曲字典中搜索键。 They keys are the song titles, and the value is the length of the song. 它们的键是歌曲标题,而值是歌曲的长度。 I want to search for the song in the dictionary, and then print out that song and its time. 我想在字典中搜索歌曲,然后打印出该歌曲及其时间。 I have figured out searching for the song, but can't remember how to bring out its value as well. 我已经想出了寻找这首歌的方法,但是想不起来如何发挥它的价值。 Here is what I currently have. 这是我目前拥有的。

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

There'no need to iterate through the dictionary keys - quick lookup is one of the main reasons for using a dictionary instead of a tuple or list. 无需遍历字典键-快速查找是使用字典而不是元组或列表的主要原因之一。

With a try/except: 尝试/除外:

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

With the dict's get method: 使用dict的get方法:

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

I don't think using try catch is good for this task. 我认为使用try catch不适合完成此任务。 Simply use the operator in 只需in

requestedSong=input("Enter song from playlist: ")
if requestedSong in songDictionary:
    print songDictionary[requestedSong]
else:
    print 'song not found'

And I strongly recommend you to read this article http://www.tutorialspoint.com/python/python_dictionary.htm 我强烈建议您阅读这篇文章http://www.tutorialspoint.com/python/python_dictionary.htm
Also check out this questions too: check if a given key exists in dictionary 也要检查一下这个问题: 检查字典中是否存在给定的键
try vs if 尝试vs如果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM