How Do I Convert A Dict That Is Wrapped In a String Back Into a Dict?

Question:
I have a variable and it has this value: '{"hi": "hello"}'. How do I convert this to {"hi":"hello"}?

To do this, you need to use the literal_eval function of the ast module. This module is built into Python, so you don’t need to import it using pip or poetry.

In your case, use this code:

import ast


string = '{"hi": "hello"}'
dictionary = ast.literal_eval(string)
print(dictionary)
1 Like

@KAlexK Thank you so much!

JSON works as well, you can do:

import json

variable = '{"hi": "hello"}'
_dict = json.loads(variable)

print(_dict)
2 Likes

I also thought about this option, but ast.literal_eval it seemed more convenient to me. In addition, json.loads can probably decrypt only dictionaries, and ast.literal_eval can also decrypt lists.

1 Like

Yes, but ast.literal_eval is overkill in this context. He is only using a string with a dictionary literal, not a list. Therefore, json.loads is a more viable option.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.