The locals()
function returns a reference to a dict
where you can inspect local variables, and each key represents the local variable name as an string:
>>> locals()
{'a': 2, 'b': 9, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
>>> var = "Some text"
>>> locals()
{'var': 'Some text', 'a': 2, 'b': 9, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
There is also the globals()
function that you can also use not only to inspect global variables but also to create new global variables dynamically:
>>> globals()['ZZ'] = 123
>>> ZZ
123
But please, don't do this. This program is unmainteinable. Use a normal dict
to create custom elements with your code. This program is way far more readable and maintainable:
list = ["a", "b", "c"]
d = {}
for item in list:
d[item] = 1
print d['a']
print d['b']
print d['c']