[Tutor] Storing dictionary value, indexed by key, into a variable

Alex Kleider akleider at sonic.net
Mon Mar 31 16:08:34 CEST 2014


On 2014-03-31 06:38, John Aten wrote:
> Hey all,
> 
> I am writing a program to drill the user on Latin demonstrative
> pronouns and adjectives (DPA). It displays a description, and the user
> has to enter the DPA that corresponds to the description. DPA vary for
> gender, number and case, and there are 3 separate DPA. I have these
> stored in a bunch of dictionaries, with the DPA, gender and number in
> the dictionary name and the cases as keys. Of course, the values are
> the DPA themselves. Like so:
> 
> that_those_Masculine_Singular = {'nom': 'ille', 'gen': 'illīus',
> 'dat': 'illī', 'acc': 'illum', 'abl': 'illō'}
> 
> I have a function that randomly selects one of these dictionaries, and
> another that randomly selects strings corresponding to the keys
> ('nom', 'gen', etc.). The trouble begins somewhere along here:
> 
> D = chooseDict()
> c = chooseCase()
> 
> print(D, c)
> 
> guess = ''
> # code to get the guess
> # then,
> answer = D[c]
> 
> if guess == answer:
> 	# Do stuff, change score, continue, etc.
> 
> This doesn't work, and I get this error:
> 
> TypeError: string indices must be integers
> 
> So my question is, why does Python think that D is a string? When I
> type the actual names (i.e., that_those_Masculine_Singular["nom"]) the
> answer is returned just fine. I have tried D['c'] and D["c"] also, and
> got the same error. I searched the web, and I can find no explanation
> on how to do what I am doing, and I can find nothing that indicates
> why this doesn't work. I'd really appreciate any help!
> 
> Thank you,
> 
> J
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

Assuming that it is the
answer = D[c]
statement is giving you the TypeError, I suggest you add the following 
print statements just before it:
print("'D' is of type %s"%(type(D), )
print("'c' = %s and is of type %s."%(c, type(c), )
You might get some surprises.



More information about the Tutor mailing list