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!

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

You are awesome! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.