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]
preezzzy
  • 598
  • 5
  • 23

3 Answers3

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"].

Kevin
  • 74,910
  • 12
  • 133
  • 166
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]
SteJ
  • 1,491
  • 11
  • 13
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')
>>> 
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • One *can*, but one shouldn't. In any case, your iterator is just a long way of writing `globals().get(name, None)`. – chepner Jul 30 '15 at 20:19