Python – Given a list of variable names in Python, how to a create a dictionary with the variable names as keys (to the variables’ values)

dictionarylistpython

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'])

Best Solution

Forget filtering locals()! The dictionary you give to the formatting string is allowed to contain unused keys:

>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> locals()
{'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...}
>>> '%(name)s %(zip)i' % locals()
'foo 123'

With the new f-string feature in Python 3.6, using locals() is no longer necessary:

>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> f'{zip: >5} {name.upper()}'
'  123 FOO'