0
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!')

Error:

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

How can retrieve value or key from the dictionary, name of which is given by user?

1
  • because your trying to lookup the a variable, which is a string. Commented Jul 27, 2014 at 23:25

1 Answer 1

1

You need to fix your dictionary so that the name of the country is also a key:

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

Now you can ask the user for the country:

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.