Frage

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!

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top