Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?

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

Asked by: John508 | Posted: 30-11-2021

Answer 1

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'

Answered by: Sienna403 | Posted: 01-01-2022

Answer 2

You can use list or generator comprehensions to build a list of key, value tuples used to directly instantiate a dict. The best way is below:

dict((name, eval(name)) for name in list_of_variable_names)

In addition, if you know, for example, that the variables exist in the local symbol table you can save yourself from the dangerous eval by looking the variable directly from locals:

dict((name, locals()[name]) for name in list_of_variable_names)

After your final update, I think the answer below is really what you want. If you're just using this for string expansion with strings that you control, just pass locals() directly to the string expansion and it will cherry-pick out the desired values

If, however, these strings could ever come from an outside source (e.g. translation files), than it's a good idea to filter locals()

Answered by: Steven925 | Posted: 01-01-2022

Answer 3

Your original list [foo, bar, baz] doesn't contain the variable names, it just contains elements that refer to the same values as the variables you listed. This is because you can have two different variable names that refer to the same value.

So, the list by itself doesn't contain information about what other names refer to the objects. The first element in your array has the name foo but it also has the name a[0] (assuming your array is called a). After executing the following code, quux also refers to the same object:

quux = a[0]

Update: You're right that you can use eval() for that, but its use is generally discouraged. Python provides a special member named __dict__ that contains the symbol table for the current module. So you can:

import __main__
d = dict((x, __main__.__dict__[x]) for x in list_of_variable_names)

Having to import __main__ when your code is in the unnamed main module is a quirk of Python.

Answered by: Fenton511 | Posted: 01-01-2022

Answer 4

Not efficient, but without invoking eval:

dict((k,v) for (k,v) in globals().iteritems() if k in list_of_variable_names)


dict((k,v) for (k,v) in vars().iteritems() if k in list_of_variable_names)

depending on what you want.

Answered by: Marcus229 | Posted: 01-01-2022

Similar questions

sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}

Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.

python - How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?

python - How can I make a dictionary from separate lists of keys and values?

I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}

python - Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom)

Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?

python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...

python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...

python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.

python - Check if a given key already exists in a dictionary and increment it

How do I find out if a key in a dictionary has already been set to a non-None value? I want to increment the value if there's already one there, or set it to 1 otherwise: my_dict = {} if my_dict[key] is not None: my_dict[key] = 1 else: my_dict[key] += 1

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python