使用Python字典将用户输入从值更改为键

使用Python字典将用户输入从值更改为键,python,python-3.x,Python,Python 3.x,我制作了一本包含不同国家的键和值的字典。e、 g 样本变量: property = ['Hub','Country','Division'] divisionlist = ['GE'] hublist = ['EUDIV'] countrylist = ['GER', 'GRE', 'HUN'] countrynamelist = ['Germany','Greece','Hungary'] 创建字典的代码: countrydict ={key:value for key, value in

我制作了一本包含不同国家的键和值的字典。e、 g

样本变量:

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'
回溯(最近一次呼叫最后一次):
文件“hello_alerts.py”,第85行,在
警报()
文件“hello_alerts.py”,第50行,在alert中
第一个值=countrydict[国家值]
关键错误:“德国”

检查该值是否存在于
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

正如您向我们展示的那样,代码不应该抛出错误。当提示输入国家名称时,我无法使用您的代码的配对版本并在我的控制台中输入“Germany”(德国)来复制KeyError。您在程序中输入的选项是什么?我运行您的代码时,没有使用属性中的
if first_属性:
,因为您没有显示它包含的内容,它正在工作-你确定上面是你的代码吗?你能准确地显示代码吗<代码>控制ICT似乎在不同的范围内。或者换一种方式——它无法识别“German”键的唯一原因是它无法在其作用域中看到
contrydict
,您为其提供了什么输入,使其崩溃?这似乎是一个很好的解决方案,尽管OP没有上传重现错误的代码。。。。