I have a list of variable names, like this:
['foo', 'bar', 'baz']
(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)
How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables?
{'foo': foo, 'bar': bar, 'baz': baz}
Now that I'm re-asking the question, I came up with:
d = {}
for name in list_of_variable_names:
d[name] = eval(name)
Can that be improved upon?
Update, responding to the question (in a comment) of why I'd want to do this:
I often find myself using the % operator to strings with a dictionary of names and values to interpolate. Often the names in the string is just the names of local variables. So (with the answer below) I can do something like this:
message = '''Name: %(name)s
ZIP: %(zip)s
Dear %(name)s,
...''' % dict((x, locals()[x]) for x in ['name', 'zip'])