Tuesday, January 30, 2007

Create a dictionary with these variables such that the keys are the variable names and the corresponding values are the variable values

> i have few variables and i want to create a dictionary with these
> variables
> such that the keys are the variable names and the corresponding values
> are the variable values.how do i do this easily?
> for ex:
> var1='mark'
> var2=['1','2','3']
> my_dict = create_my_dictionary(var1, var2)
>
> and my_dict is {'var1':'mark', 'var2':['1','2','3']}
>
> is there a function for create_my_dictionary?

var1='mark'
var2=['1','2','3']
my_dict = dict(var1=var1, var2=var2)

In addition, if you are inside a function, and these are the only
variables, using locals() may be useful too:

def f():
a = 1
b = 2
c = locals()
print c
d = 3

prints {'a': 1, 'b': 2}

No comments: