1

I have string "dict_1", and I have dictionary named dict_1.

x = "dict_1"
dict_1 = {"a": "b", "c": "d"}

So, can I access dict_1 like x['a']?

I found a Stack Overflow Question, but in this question, the OP wants to create variable with string, not access variable (dictionary) with string.

I really need some help. I'm using Python 3.8 and Windows.

Thanks!

costaparas
  • 5,047
  • 11
  • 16
  • 26
Superjay
  • 447
  • 1
  • 7
  • 25

1 Answers1

3

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"
costaparas
  • 5,047
  • 11
  • 16
  • 26