首页 > 解决方案 > 使用 Python 字典将用户输入从值更改为键

问题描述

我制作了一个字典,其中包含不同国家的键和值。例如

样本变量:

property = ['Hub','Country','Division']
divisionlist = ['GE']
hublist = ['EUDIV']
countrylist = ['GER', 'GRE', 'HUN']
countrynamelist = ['Germany','Greece','Hungary']

制作字典的代码:

countrydict ={key:value for key, value in zip(countrynamelist,countrylist)} 

字典可视化:

countrydict = {'Germany': 'GER', 'Greece': 'GRE', 'Hungary': 'HUN'}

从函数中提取:

while True:
        print("Select between a 'Hub','Country' or 'Division'")
        first_property = input('Enter a property name: ').capitalize()
        if first_property in property:
            break
        else:
            continue
    if first_property == 'Hub':
        print('Available hubs: ', hublist)
        first_value = input('Enter a hub name: ').upper()
    if first_property == 'Country':
        country_value = input('Enter a country name: ').capitalize()
        first_value = countrydict[country_value]
    if first_property == 'Division':
        print('Available divisions: ', divisionlist)
        first_value = input('Enter a division name: ').upper()

我试图让用户输入国家名称而不是首字母缩写词,因为这样更容易。但是我收到了这个错误

Traceback (most recent call last):
  File "hello_alerts.py", line 85, in <module>
    alert()
  File "hello_alerts.py", line 50, in alert
    first_value = countrydict[country_value]
KeyError: 'Germany'

标签: pythonpython-3.x

解决方案


检查该值是否存在于 中countrydict,如果不存在,则可能分配一个NA字符串:

if country_value in countrydict:
    first_value = countrydict[country_value]
else:
    first_value = "NA"
print(first_value)

输出:

Enter a country name: Germany
GER

推荐阅读