2

I have some issues with the eval function. I have a list like, for example,

list1 = [('a',1), ('b',2), ('c',3)]

and I would like to assign each value of a tuple to the first element:

for el in list1 :
    eval(el[0]) = el[1]

How can I do this?

Chris
  • 44,602
  • 16
  • 137
  • 156
NicoCati
  • 527
  • 1
  • 8
  • 11

2 Answers2

12

You could do this:

exec('%s = %s' % el)

But don't. Really, don't. You don't need dynamic local variables, you need a dictionary:

my_dict = dict(list1)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • +1 [Is Using eval In Python A Bad Practice?](http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice) – gecco Jan 11 '12 at 11:23
  • 1
    `eval` works only on expressions. That would need `exec`. Still, he shouldn't do that :P – Ricardo Cárdenes Jan 11 '12 at 11:39
  • using dictionaries is best. That way you have the keys and the values together in a single variable and also you can access them separately using keys() and values() if you need to. – Arnab Ghosal Jan 11 '12 at 12:50
4

You don't need eval for that.

You can access local environment directly by calling the vars builtin. Here's an example interactive session:

>>> list1 = [("a", 4), ("b", 8)]
>>> vars().update(dict(list1))
>>> a
4
>>> b
8

Here vars() returns the dict with local variable bindings. Since it returns a pointer to the only instance (not a copy), you can modify it in place (.update).

Mischa Arefiev
  • 5,227
  • 4
  • 26
  • 34
  • While this is true, and does answer his question, you really shouldn't do that. Must better to just create a new dictionary for them. – Shawabawa Jan 11 '12 at 13:48
  • 1
    According to the [`vars()` documentation](https://docs.python.org/2/library/functions.html#vars): "Without an argument, `vars()` acts like `locals()`. Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored." – martineau Oct 10 '16 at 15:50