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

时间:2019-02-20 14:22:03

标签: python python-3.x

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

样本变量:

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'

1 个答案:

答案 0 :(得分:1)

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