-4

I have a list which includes some values such as

tableVal = ['val1', 'val2', 'val3']

I want to use each element as a variable and, assign correspondingly as parameter of a function such as:

for i in tableVal:
    i = myFunc(print "this is your value: "+ i)

So when I type >> val1, it should return this is your value: val1. How can I do that?

tso
  • 4,732
  • 2
  • 22
  • 32
ylcnky
  • 775
  • 1
  • 10
  • 26
  • 2
    Is there a reason you feel that using a dict to do something similar won't work? – cwallenpoole Jan 08 '18 at 14:19
  • Please indent code by 4 spaces instead of using ``. – internet_user Jan 08 '18 at 14:20
  • Possible duplicate of https://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name? – pstatix Jan 08 '18 at 14:23
  • 3
    Possible duplicate of [To convert string to variable name](https://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name) – pstatix Jan 08 '18 at 14:23
  • Do you want 'val1' to become a function (so `val1()` returns or print something), a variable (like `val1 = "this is you value: val1"`), or do you want to print more text when typing 'val1' in the console (without really modifying val1) ? – Mel Jan 08 '18 at 14:27
  • `globals().update(dict((i, 'this is your value: {}'.format(i)) for i in tableVal))`? – Stop harming Monica Jan 08 '18 at 14:43
  • @Goyo, with slight modification for the real problem context it solved. Thanks, can you update as reply so I can accept?. And it is surprising four minus voting just because of duplication? – ylcnky Jan 08 '18 at 20:31

2 Answers2

1

As hinted in the comments, the proper way of mapping names to values dynamically is using a dictionary:

d = dict((i, 'this is your value: {}'.format(i)) for i in tableVal)
print d['val1']

Output:

this is your value: val1

You can add this mapping to globals() so your names become global variables:

globals().update(d)
print val1

Output:

this is your value: val1

But this is almost always a bad idea. Other people will not expect variables being magically created and they might shadow pre-existing variables. You can mitigate the risk by putting them in their own namespace:

class Namespace(object):
    def __init__(self, d):
        vars(self).update(d)

n = Namespace(d)
print n.val1

This allow you to use autocomplete in an IDE or the IPython shell without polluting your global namespace.

An even better alternative using the standard library, if immutability is OK, is collections.namedtuple:

n = namedtuple('Namespace', tableVal)(*d.values())
print n.val1
Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
0

You can use a lambda function with a dictionary:

tableVal = ['val1', 'val2', 'val3']
new_table = {i:(lambda x: lambda :"this is your value: {}".format(x))(i) for i in tableVal}
new_table['val2']()

Output:

this is your value: val2
Ajax1234
  • 69,937
  • 8
  • 61
  • 102