dynamic assigments

scattered tooscattered at gmail.com
Thu Mar 24 17:39:34 EDT 2011


On Mar 24, 2:39 pm, Seldon <sel... at katamail.it> wrote:
> Hi, I have a question about generating variable assignments dynamically.
>
> I have a list of 2-tuples like this
>
> (
> (var1, value1),
> (var2, value2),
> .. ,
> )
>
> where var1, var2, ecc. are strings and value1, value2 are generic objects.
>
> Now, I would like to use data contained in this list to dynamically
> generate assignments of the form "var1 = value1", ecc where var1 is an
> identifier equal (as a string) to the 'var1' in the list.
>
> Is there a way to achieve this ?
>
> Thanks in advance for any answer.

Could try:

>>> my_list = [("x", 7), ("y", 8)]

>>> for pair in my_list: exec(pair[0] + " = " + str(pair[1]))

>>> x,y

>>> (7,8)






More information about the Python-list mailing list