Assuming your goal is to be able to access a variable with a dynamic name, the only solution that works at global, nested and local scope without a lot of fallback code (to handle both local and globally scoped names) is to use eval
:
dictionary1 = {'a':1,'b':2}
p1 = 'dictionary'
p2 = 1
union = p1+str(p2)
for key, value in eval(union).items():
print key, value
All eval(union)
does is execute the contents of the string referenced by union
as if it were a Python expression; as it happens, the name of a variable is a perfectly legal Python expression, so it's legal, if not super-safe, to use eval
to perform the lookup for you.
If the variable is known to be in local or global scope already, you could do:
for key, value in locals()[union].items():
for key, value in globals()[union].items():
which is safer (in that it can't execute arbitrary code like eval
can), but won't dynamically check local, nested and global scopes (any such checks would have to be performed manually, and nested scope would be ugly).
Note that in general, this is a bad idea. If you need to access variables by name, just make a dictionary mapping names (as strings) to the values you care about. Then you can use code like this safely, without the eval
security/stability risks:
mydicts = {'dictionary1': {'a':1,'b':2}}
p1 = 'dictionary'
p2 = 1
union = p1+str(p2)
# If union is not a string in the dictionary, this will raise KeyError,
# but can't execute arbitrary code
for key, value in mydicts[union].items():
print key, value