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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)