【问题标题】:Searching for key in dictionary, and printing the key and its value在字典中搜索键,并打印键及其值
【发布时间】:2015-11-22 23:40:02
【问题描述】:

我正在尝试在歌曲词典中搜索关键字。它们的键是歌曲名称,值是歌曲的长度。我想在字典中搜索这首歌,然后打印出那首歌和它的时间。我已经想通了搜索这首歌,但不记得如何带出它的价值。这是我目前拥有的。

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

【问题讨论】:

    标签: python search dictionary key


    【解决方案1】:

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

    尝试/排除:

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

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-12
        • 1970-01-01
        • 1970-01-01
        • 2020-02-16
        • 1970-01-01
        • 2014-11-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多