create dictionary from list of variables
You can't do it without writing at least the variable names, but a shorthand can be written like this:
>>> foo = 1
>>> bar = 2
>>> d = dict(((k, eval(k)) for k in ('foo', 'bar')))
>>> d
{'foo': 1, 'bar': 2}
or as a function:
def createDict(*args):
return dict(((k, eval(k)) for k in args))
>>> createDict('foo','bar')
{'foo': 1, 'bar': 2}
you can also use globals()
instead of eval()
:
>>> dict(((k, globals()[k]) for k in ('foo', 'bar')))
pip install sorcery
from sorcery import dict_of
a = 1
b = 2
c = 3
d = dict_of(a, b, c)
print(d)
# {'a': 1, 'b': 2, 'c': 3}