[英]Changing user input from value to key using Python dictionary
I have made a dictionary that contains keys and values of different countries. 我制作了一部包含不同国家的键和值的字典。 eg
例如
Sample variables: 样本变量:
property = ['Hub','Country','Division']
divisionlist = ['GE']
hublist = ['EUDIV']
countrylist = ['GER', 'GRE', 'HUN']
countrynamelist = ['Germany','Greece','Hungary']
Code to make dictionary: 制作字典的代码:
countrydict ={key:value for key, value in zip(countrynamelist,countrylist)}
Dictionary visualised: 可视化的词典:
countrydict = {'Germany': 'GER', 'Greece': 'GRE', 'Hungary': 'HUN'}
Extract from a function: 从函数中提取:
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()
I'm trying to allow users to input the name of the country instead of the acronym, as it is easier. 我正在尝试允许用户输入国家名称而不是首字母缩写,因为这样更容易。 However I'm getting this error
但是我遇到这个错误
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'
Check if the value exists in the countrydict
, and if it does not, maybe assign a NA
string: 检查
countrydict
是否存在该值,如果不存在,则可以分配一个NA
字符串:
if country_value in countrydict:
first_value = countrydict[country_value]
else:
first_value = "NA"
print(first_value)
OUTPUT: 输出:
Enter a country name: Germany
GER
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.