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

Peter Otten __peter__ at web.de
Mon Mar 31 16:18:58 CEST 2014


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:

Unfortunately the problem is in the code you don't show. You might add the 
line

> D = chooseDict()

  print("D is of type", type(D))

and if that prints

D is of type <class 'str'>

you can be sure that the problem originates in the chooseDict() function.
Try to find the error yourself first, looking closely at the function's 
code, and if you run out of ideas or places where you can put print() calls 
for debugging purposes come back here. Don't forget to include the code this 
time.

> 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

As a general note, error messages are most useful when the are accompanied 
by the traceback. As it stands I have no idea what line triggers the error; 
you might have the line

""[""]

somewhere in your code.

> 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!

If the D in the line

D = chooseDict()

is actually a dict you are most certainly reassigning 

D = "some string"

or you have two different variables named "D" in separate scopes.




More information about the Tutor mailing list