To convert a string to a dictionary in Python, you can use the “json.loads()” function from the json module if the string is in a JSON-compliant format.
import json
str = '{"Name": "Millie", "Age": 18, "City": "Atlanata"}'
print('The JSON String is', str)
convertedDict = json.loads(str)
print("After conversion: ", convertedDict)
print(type(convertedDict))
Output
The JSON String is {"Name": "Millie", "Age": 18, "City": "Atlanata"}
After conversion: {'Name': 'Millie', 'Age': 18, 'City': 'Atlanata'}
<class 'dict'>
Alternate methods
Using ast.literal_eval() function
The ast.literal_eval() is a built-in Python library function that converts a string to a dict.
To use the literal_eval() function, import the ast package and use its literal_eval() method.
import ast
str = '{"Name": "Millie", "Age": 18, "City": "Atlanata"}'
print('The JSON String is', str)
convertedDict = ast.literal_eval(str)
print("After conversion: ", convertedDict)
print(type(convertedDict))
Output
The JSON String is {"Name": "Millie", "Age": 18, "City": "Atlanata"}
After conversion: {'Name': 'Millie', 'Age': 18, 'City': 'Atlanata'}
<class 'dict'>
Using generator expressions in Python
If we have enough strings to form a dictionary, use the generator expressions to convert the string to a dictionary.
str = "E - 11, K - 19, L - 21"
convertedDict = dict((x.strip(), int(y.strip()))
for x, y in (element.split('-')
for element in str.split(', ')))
print("Converted dict is: ", convertedDict)
print(type(convertedDict))
Output
Converted dict is: {'E': '11', 'K': '19', 'L': '21'}
<class 'dict'>
Conclusion
The easiest way is to use the json.loads() function to convert a valid string to a dict in Python.
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Hi,
thank you !
i have an other expression to convert to dict like this :
can you help me please?
resu = {
“list_file”:”{
\”iross\”: [
\”artt\”,
\”artction\”,
\”artiong\”,
\”artiype\”,
\”coon\”,
\”colleong\”,
\”collype\”,
\”genre\”,
\”genst\”,
\”genction\”,
\”rle\”,
\”sog\”,
\”storont\”,
\”mepe\”,
],
\”mch\”: [\”mach\”, \”coltch\”, \”stch\”],
\”popularity\”: [\”album_poe\”, \”song_populanre\”]
}”}