【问题标题】:My search input functions works, but it only prints the last person's information in the list of dicts我的搜索输入功能有效,但它只打印字典列表中的最后一个人的信息
【发布时间】:2020-02-01 01:40:38
【问题描述】:

我对 python 有点陌生,我需要一些帮助。我正在制作员工列表菜单。我的字典列表是:

person_infos = [ {'name': 'John Doe', 'age': '46', 'job position': 'Chair Builder', 'pay per hour': '14.96','date hired': '2/26/19'},

  {'name': 'Phillip Waltertower', 'age': '19', 'job position': 'Sign Holder', 'pay per hour': '10','date hired': '5/9/19'},

  {'name': 'Karen Johnson', 'age': '40', 'job position': 'Manager', 'pay per hour': '100','date hired': '9/10/01'},

  {'name': 'Linda Bledsoe', 'age': '60', 'job position': 'CEO', 'pay per hour': '700', 'date hired': '8/24/99'},

  {'name': 'Beto Aretz', 'age': '22', 'job position': 'Social Media Manager', 'pay per hour': '49','date hired': '2/18/12'}]

我的“搜索字典输入功能列表”是程序应该如何根据用户输入的名称打印正确的字典:

def search_query(person_infos):
  if answer == '3':
    search_query = input('Who would you like to find: ')
    they_are_found = False
    location = None
    for i, each_employee in enumerate(person_infos):
      if each_employee['name'] == search_query:
        they_are_found = True
      location = i
    if they_are_found:
      print('Found: ', person_infos[location]['name'], person_infos[location]['job position'], person_infos[location]['date hired'], person_infos[location]['pay per hour'])
  else:
      print('Sorry, your search query is non-existent.')

我也有这个-

elif answer =='3':
  person_infos = search_query(person_infos)

这似乎是朝着正确方向迈出的一步,但对于

search_query = input('Who would you like to find: ')

如果我在person_infos 中输入名称,例如“John Doe”,它只会打印最后一个字典的信息(无论是哪个特定字典,都会输出顺序中的最后一个)而不是 John做。在这种情况下,它只会打印“Beto Aretz's”。 有人可以帮忙吗?这是我一直在努力奋斗的事情,它会很棒。 我研究了很多,但我找不到我知道该怎么做或输入搜索的东西。

谢谢, 左路

【问题讨论】:

    标签: python dictionary search printing conditional-statements


    【解决方案1】:

    乍一看,这似乎是因为您的 location=i 没有在 if 语句中缩进,因此在 for 循环的每次迭代中它都被设置为最新的 i。让我知道这是否有帮助。

    def search_query(person_infos):
      if answer == '3':
        search_query = input('Who would you like to find: ')
        they_are_found = False
        location = None
        for i, each_employee in enumerate(person_infos):
          if each_employee['name'] == search_query:
            they_are_found = True
            location = i
        if they_are_found:
          print('Found: ', person_infos[location]['name'], person_infos[location]['job position'], person_infos[location]['date hired'], person_infos[location]['pay per hour'])
      else:
          print('Sorry, your search query is non-existent.')
    

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2019-02-26
      相关资源
      最近更新 更多