Python variables as keys to dict
The globals()
function returns a dictionary containing all your global variables.
>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}
There is also a similar function called locals()
.
I realise this is probably not exactly what you want, but it may provide some insight into how Python provides access to your variables.
Edit: It sounds like your problem may be better solved by simply using a dictionary in the first place:
fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3
A one-liner is:-
fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))
Here it is in one line, without having to retype any of the variables or their values:
fruitdict.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'fruitdict'})
for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]