【问题标题】:How to create a dictionary that allows multiple keys in a user input and print out key values combined in one string?如何创建允许用户输入中的多个键并打印出组合在一个字符串中的键值的字典?
【发布时间】:2021-07-02 22:29:43
【问题描述】:

我坚持使用 python 字典,感谢您的帮助,因为我没有在互联网上找到任何类似问题的示例。

我正在尝试创建一个允许的程序

  1. 在用户输入字段中输入多个键
  2. 然后打印出在一个字符串中输入的键的所有值。

例如,如果用户输入“country1, country2, country3”,程序会打印出“'location1', 'location2', 'location3'。

在下面的代码中,它只允许一个国家和打印出一个位置。我尝试了使用列表、字典、元组的不同方法 - 无法弄清楚。

country_dict = {
'country1': 'location1',
'country2': 'location2',
'country3': 'location3',
}

country = input("Enter country: ")
if country.lower() == 'country1':
    country_dict['country1']
if country.lower() == 'country2':
    country_dict['country2']
if country.lower() == 'country3':
    country_dict['country3']

print (country_dict[country])

【问题讨论】:

    标签: python list dictionary tuples key


    【解决方案1】:

    试试下面的注释代码:

    countries = input("Enter country: ").split(',') # split the input based on ,
    result = []
    for c in countries: # iterate over the input countries
        result.append(country_dict.get(c.strip().lower(), '')) # get value from the dict, empty string if key is not found
    
    print(', '.join(result)) # join the result using ', ' 
    

    【讨论】:

    • 这很好用,非常感谢你,克里希纳!
    【解决方案2】:
    #declare country_dict
    country_dict = {
    'country1': 'location1',
    'country2': 'location2',
    'country3': 'location3',
    }
    #take input country(s)
    country = input("Enter country: ")
    out=[]
    for i in country.split(","): #Change split string based on your requirement
        out.append(country_dict[i])
    
    print (",".join(out)) #change join string based on your requirement
    

    【讨论】:

      【解决方案3】:

      您可以解析您的输入,然后查找位置:

      country_dict = {
      'country1': 'location1',
      'country2': 'location2',
      'country3': 'location3',
      }
      
      country = input("Enter country: ")
      countries = country.split()
      locations = ''
      for key in country_dict.keys():
          if key in countries:
              locations += f'{country_dict[key]} '
      
      print(locations)
      

      示例: 输入:country1 country2 输出:location1 location2

      【讨论】:

      • 感谢您的帮助,大卫!工作和优雅的解决方案!
      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 2019-12-12
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 2021-03-04
      • 2020-09-30
      相关资源
      最近更新 更多