1

So I'm not sure how to describe this or google it. What i want is to use a variable to access another variable. I'm guessing the answer will be using a dictionary of sorts.

personPaul = [1,2]
personJoe = [3,4]

def myFunc(name):
    return person + name

print myFunc("Paul")
print myFunc("Joe")

I want the output to be

[1,2]
[3,4]
2

3 Answers 3

4

I'm guessing the answer will be using a dictionary of sorts

Exactly right :-)

people = {
    "Paul": [1,2],
    "Joe": [3,4]
}

def myFunc(name):
    return people[name]

print myFunc("Paul")
print myFunc("Joe")

Of course, you can also cut out the myFunc middleman and directly do print people["Paul"].

Sign up to request clarification or add additional context in comments.

1 Comment

Or a compromise: myFunc = people.get.
2

Is this what you are after?:

people = {
    "Paul":[1,2],
    "Joe":[3,4]
}
print people["Paul"] # Gives you [1,2]
print people["Joe"] # Gives you [3,4]

Comments

1

You can use globals() function to access to global variables inside the function and then use a generator expression within next function to loop over its items then check if your name is in a global name (the key) then print its corresponding value :

>>> personPaul = [1,2]
>>> personJoe = [3,4]
>>> def myFunc(name):
...     return next((v for k,v in globals().items() if name in k),None)
... 
>>> myFunc('Paul')
[1, 2]
>>> myFunc('jack')
>>> 

1 Comment

One can, but one shouldn't. In any case, your iterator is just a long way of writing globals().get(name, None).

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.