0

I am facing the following problem;

Somewhere inside my script I have defined a function

def lookup(type, value): 
    doctors = {'doctor1':"Smith", 'doctor2':"Rogers"}
    supervisors = {'super1': "Steve", 'super2': "Annie"}
    print type['value']

I am calling this function from the end of my script like this:

myDoc = 'super1'
lookup('supervisors', myDoc)

However I get the following error:

TypeError: string indices must be integers, not str

Why is that happening and how may I fix it?

Thank you all in advance!

stratis
  • 7,750
  • 13
  • 53
  • 94
  • just changed the myDoc value which had been set to a wrong value. Now my point should be more clear. – stratis Mar 11 '13 at 21:11

1 Answers1

5

Don't try to look up local variables from a string. Just store your doctors and supervisors in a nested dictionary:

def lookup(type, value): 
    people = {
        'doctors': {'doctor1': "Smith", 'doctor2': "Rogers"},
        'supervisors': {'super1': "Steve", 'super2': "Annie"}
    }
    print people[type][value]

which results in:

>>> myDoc = 'super1'
>>> lookup('supervisors', myDoc)
Steve

In the rare case that you do need to refer to a local variable dynamically, you can do that with the locals() function, it returns a dictionary mapping local names to values. Note that within functions, changes to the locals() mapping are not reflected in the function local namespace.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Sorry :)) I just discarded an identical post, I had to do *something* :) – Pavel Anossov Mar 11 '13 at 21:08
  • @PavelAnossov: I tend to edit in corrections and additional info in the first few minutes, it's a little disconcerting when I am being informed of new edits all the time.. – Martijn Pieters Mar 11 '13 at 21:10
  • Thank you! Works fine now! However I still haven't quite understood why it was not working before... – stratis Mar 12 '13 at 07:40
  • 1
    @Konos5: `type` was a reference to a string (`'supervisors'` in your example). Calling `type['value']` means index whatever is in `type` with the key `'value'` (a string literal). That would work if `type` was a dictionary (`type = {'value': 'foobar'}` for example), but doesn't work for a string. Python strings are sequences (just like lists and tuples), so you can only use integers as indexes for those; `type[0]` would be the first character `'s'`, etc. This all had nothing to do with what you were trying to achieve, `type` was never going to magically point to the `supervisors` local var. – Martijn Pieters Mar 12 '13 at 10:04
  • Excellent. It all makes sense now. Thank for your clear and informative answers. – stratis Mar 12 '13 at 20:28