Convert string to dictionary using eval() function.

There is situation where you need to convert string to dictionary, your string must contain a valid dict. By using eval() function we can easily get a valid dict. It also check the validity of string having dictionary.

e.g. you have a string;

init_string = “{‘name’: ‘Jhon’, ‘age’: 12, ‘passport_no’: ‘123456789’}”

print(type(init_string))
print(init_string)
#using eval, we can get dict out of string
print(type(
eval(init_string)))
print(
eval(init_string))

Output:

<class ‘str’>
{‘name’: ‘Jhon’, ‘age’: 12, ‘passport_no’: ‘123456789’}
<class ‘dict’>
{‘name’: ‘Jhon’, ‘age’: 12, ‘passport_no’: ‘123456789’}

print(init_string)

print(type(eval(init_string)))