繁体   English   中英

使用用户输入从字典中获取值

[英]Getting values from dictionary using user input

Bavaria={'Number_of_solders':1500, 'Strength':5}
print ('Which country is attacking? ')
a=input()
print ('Number of attacking forces of '+a+' is '+a['Number_of_soldiers']+' men!')

错误:

Traceback (most recent call last):
                                  line 6, in <module>
    print ('Number of attacking forces of '+a+' is '+a['Number_of_soldiers']+' men!')
TypeError: string indices must be integers

如何从字典中检索名称由用户指定的值或键?

您需要修复字典,以便国家/地区名称也是关键:

countries = {'bavaria': {'soldiers': 1500, 'strength': 5}}

现在,您可以向用户询问国家/地区:

a = input('Which country is attacking? ')
stats = countries.get(a.lower())
if stats:
    print('Number of soliders: {0[soldiers]} men!'.format(stats))
else:
    print('Sorry no stats for {0}'.format(a))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM