Is there an idiomatic way to build a dictionary with variable names as keys and values as values?


Sonomad

Is there an idiomatic (maybe more Pythonic) way to handle this:

title = "my title"
name = "my name"
# [... on and on ...]

my_dict = {
    'title': title,
    'name': name,
    # and on and on
}

Basically, the variable name (by encoding) is the key and the variable value is the value?

Vedrak

In Python, objects don't have names, and their names are not known. titleSo you can't deduce the string given the situation "title".

Scope( globals, locals, vars) associates names with objects , so any such hack must go through the scope. One way is:

title = "my title"
name = "my name"

things_I_want = "title", "name"
scope = vars()
{name: scope[name] for name in things_I_want}
#>>> {'title': 'my title', 'name': 'my name'}

Of course, this is not satisfactory. The right way goes a long way.

Related


Is there a way to use variable values as variable names in bash?

Shiva I am trying to solve a very strange problem. I am trying to accomplish something like this, # loaded ahead of time silly1_cred="secret" silly2_cred="password" important_var="silly1" #known at run time cred=`echo ${important_var}_cred` #now value of cred