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)))

Muhammad Atif

Technical Consultant / Odoo Python Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store