How to Convert String to Dictionary in Python
To convert a string to a dictionary in Python, you can use the ast.literal_eval() function or the json.loads() function.
The following examples show how to convert a string to a dictionary in Python using these two methods.
Using ast.literal_eval() Function
We can use the ast.literal_eval() function to convert a string to a dictionary.
Suppose we have the following string:
import ast
# Declare string
dict1_string = '{"Emp_Id": "A-12", "Joining_Date": "11/12/2021", "Emp_Name": "Anita Pawar", "Past_Exp": 2, "Department": "R&D", "Age": 25}'
# Convert string to dictionary
dict1 = ast.literal_eval(dict1_string)
# Show dictionary
print(dict1)
Output: 👇️
{'Emp_Id': 'A-12', 'Joining_Date': '11/12/2021', 'Emp_Name': 'Anita Pawar', 'Past_Exp': 2, 'Department': 'R&D', 'Age': 25}
In this example, we use the ast.literal_eval() function to convert the string dict1_string to a dictionary dict1. The output shows the dictionary created from the string using the ast.literal_eval() function.
Using json.loads() Function
We can use the json.loads() function to convert a string to a dictionary.
Suppose we have the following string:
import json
# Declare string
dict1_string = '{"Emp_Id": "A-12", "Joining_Date": "11/12/2021", "Emp_Name": "Anita Pawar", "Past_Exp": 2, "Department": "R&D", "Age": 25}'
# Convert string to dictionary
dict1 = json.loads(dict1_string)
# Show dictionary
print(dict1)
Output: 👇️
{'Emp_Id': 'A-12', 'Joining_Date': '11/12/2021', 'Emp_Name': 'Anita Pawar', 'Past_Exp': 2, 'Department': 'R&D', 'Age': 25}
In this example, we use the json.loads() function to convert the string dict1_string to a dictionary dict1. The output shows the dictionary created from the string using the json.loads() function.
Conclusion
We can use the ast.literal_eval() function or the json.loads() function to convert a string to a dictionary in Python. These methods provide a convenient way to handle string-to-dictionary conversions.