The way I see it, you have two basic options here.
The most obvious way is to use eval
to convert the value of the string x
into a usable Python object - in this case the dictionary dict_1
.
Note that eval
executes a string as Python code. If the string is coming from an untrusted source, then this is quite dangerous to do. You should use this with caution, and apply appropriate sanitization to any inputs.
x = "dict_1"
dict_1 = {"a": "b", "c": "d"}
print(type(eval(x)))
# Prints <class 'dict'>
print(eval(x)['a'])
# Prints "b"
The other method is to make use of locals()
. This returns a dictionary of variables defined in the local scope. You would index it with x
, which would give you the dictionary itself as with eval
.
x = "dict_1"
dict_1 = {"a": "b", "c": "d"}
print(type(locals()[x]))
# Prints <class 'dict'>
print(locals()[x]['a'])
# Prints "b"
In theory, using locals()
for the job would prove to be safer since with eval
, you may inadvertently execute arbitrary code.
Once again, if coming from an untrusted source, you should do some basic sanity checks, e.g. check that the variable is in scope and is a dictionary:
if x in locals() and type(locals()[x]) == dict:
print(locals()[x]['a'])
# Prints "b"