Creating variables from dicts

Hai Vu wuhrrr at gmail.com
Tue Feb 23 16:21:36 EST 2010


On Feb 23, 12:53 pm, vsoler <vicente.so... at gmail.com> wrote:
> Hi,
>
> I have two dicts
>
> n={'a', 'm', 'p'}
> v={1,3,7}
>
> and I'd like to have
>
> a=1
> m=3
> p=7
>
> that is, creating some variables.
>
> How can I do this?

I think you meant to use the square brackets [ ] instead of the curly
ones { } to define the list:

>>> n = ['a', 'b', 'c']
>>> v = [3, 5, 7]
>>> for x, y in zip(n, v):
...  exec '%s=%d' % (x, y)
...
>>> a
3
>>> b
5
>>> c
7

---
The key is the use of the exec statement, which executes the strings
"a=3", "b=5", ... as if they are python statements.



More information about the Python-list mailing list