Python variables as keys to dict
for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]
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