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

时间:2014-07-27 23:19:27

标签: python python-3.x dictionary

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

如何从字典中检索值或密钥,其名称由用户提供?

1 个答案:

答案 0 :(得分:1)

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

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))
相关问题