python - 使用 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'
解决方案
检查该值是否存在于 中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
推荐阅读
- php - 使用 WooCommerce 订单项获取特定数据结构
- python-3.x - 如何将多个数字转换为 ASCII?
- javascript - 调试以发现 onscroll 在生产和开发站点之间不起作用
- excel - 在 excel 中查找数据的脚本与 xml 进行比较并替换
- excel - =VLOOKUP("*"&... 无法正常工作我做错了什么?
- java - lombok 中的@Delegate 和@Builder 组合
- c# - 在表中的列值中正确使用列表?
- php - 如何在 Google Chart 上显示特定/特定的图例
- python - mongodb 副本集可以安全地用于 Internet 上的资源冗余吗?
- tiff - Exif IFD 可以包含另一个 Exif IFD 吗?