【问题标题】:How to search through dictionaries?如何通过字典搜索?
【发布时间】:2015-03-29 11:36:07
【问题描述】:

我是 Python 字典的新手。我正在制作一个简单的程序,该程序有一个字典,其中包括四个名称作为键和相应的年龄作为值。我想要做的是,如果用户输入一个名称,程序会检查它是否在字典中,如果是,它应该显示有关该名称的信息。

这是我目前所拥有的:

def main():
    people = {
        "Austin" : 25,
        "Martin" : 30,
        "Fred" : 21,
        "Saul" : 50,
    }

    entry = input("Write the name of the person whose age you'd like to know, or write 'ALL' to see all names and ages: ")
    if entry == "ALL":
        for key, value in people.items():
            print ("Name: " + key)
            print ("Age: " + str(value) + "\n")
    elif people.insert(entry) == True:
                print ("It works")

main()

我尝试使用 .index() 搜索字典,因为我知道它在列表中使用,但它没有用。我也试过检查this post,但没有发现它有用。

我需要知道是否有任何功能可以做到这一点。

【问题讨论】:

  • 为什么需要函数?人[条目]
  • 您可以使用以下语法在 python dict 中查找一个值:dict[key] 如果键不在字典中,则会引发 KeyError,例如people['Austin'] 或者您可以使用 get(key) 方法,如果密钥不在字典中,则返回 None ,例如people.get("Austin")

标签: python search dictionary


【解决方案1】:

够简单

if entry in people:
    print ("Name: " + entry)
    print ("Age: " + str(people[entry]) + "\n")

【讨论】:

    【解决方案2】:

    如果您想知道key 是否是people 中的一个键,您可以简单地使用表达式key in people,如:

    if key in people:
    

    并测试它是否不是 people 中的键:

    if key not in people:
    

    【讨论】:

      【解决方案3】:

      您可以直接引用这些值。例如:

      >>> people = {
      ... "Austun": 25,
      ... "Martin": 30}
      >>> people["Austun"]
      

      或者你可以使用people.get(<Some Person>, <value if not found>)

      【讨论】:

        【解决方案4】:

        Python 还支持枚举循环遍历字典。

        for index, key in enumerate(people):
            print index, key, people[key]
        

        【讨论】:

          【解决方案5】:

          你可以这样做:

          #!/usr/bin/env python3    
          
          people = {
              'guilherme': 20,
              'spike': 5
          }
          
          entry = input("Write the name of the person whose age you'd like to know, or write 'ALL' to see all names and ages: ")
          
          if entry == 'ALL':
              for key in people.keys():
                  print ('Name: {} Age: {}'.format(key, people[key]))
          
          if entry in people:
              print ('{} has {} years old.'.format(entry, people[entry]))
          else:
              # you can to create a new registry or show error warning message here.
              print('Not found {}.'.format(entry))
          

          【讨论】:

            【解决方案6】:

            这里的所有答案,为什么不:

            try:
                age = people[person_name]
            except KeyError:
                print('{0} is not in dictionary.'.format(person_name))
            

            在 Python 中测试某些内容是否在字典中的规范方法是尝试访问它并处理故障 -- It is easier to ask for forgiveness than permission (EAFP)

            【讨论】:

              【解决方案7】:

              一种可能的解决方案:

              people = {"Austin" : 25,"Martin" : 30,"Fred" : 21,"Saul" : 50,}
              
              entry =raw_input ("Write the name of the person whose age you'd like 
              to know, or write 'ALL' to see all names and ages: ")
              
              if entry == 'ALL':
              
                  for key in people.keys():
                      print(people[key])
              
              else:
              
                  if entry in people:
                      print(people[entry])
              

              【讨论】:

                猜你喜欢
                • 2019-09-12
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-04-10
                • 1970-01-01
                • 2021-12-18
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多