I\'m looking for a way to create dictionary without writing the key explicitly I want to create function that gets number variables, and create dictionary where the variables na
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')))