In Python, sometimes a string represents nested dictionary data. For example, the string might look like "{'a': {'b': {'c': 1}}}". The task is to convert this string into an actual nested dictionary. Let's explore several methods to achieve this.
Using ast.literal_eval
This method uses the literal_eval function from the ast module to safely evaluate the string and convert it to a nested dictionary.
import ast
# Input string
s = "{'a': {'b': {'c': 1}}}"
# Converting string to nested dictionary
d = ast.literal_eval(s)
print(d)
Output
{'a': {'b': {'c': 1}}}
Explanation:
- ast.literal_eval function parses the string and evaluates it as a Python literal, converting it to a nested dictionary.
- This method is safe and handles nested structures efficiently.
Let's explore some more ways and see how we can convert string to nested dictionaries.
Table of Content
Using json.loads with String Replacement
This method uses the json.loads function after replacing single quotes with double quotes to match JSON format requirements.
import json
# Input string
s = "{'a': {'b': {'c': 1}}}"
# Converting string to nested dictionary
d = json.loads(s.replace("'", '"'))
print(d)
Output
{'a': {'b': {'c': 1}}}
Explanation:
- JSON requires keys and strings to be enclosed in double quotes. The replace method replaces single quotes with double quotes.
- The json.loads function then parses the string into a nested dictionary.
Using eval()
This method uses the built-in eval() function to directly evaluate the string into a Python object.
# Input string
s = "{'a': {'b': {'c': 1}}}"
# Converting string to nested dictionary
d = eval(s)
print(d)
Output
{'a': {'b': {'c': 1}}}
Explanation:
- eval() function evaluates the string as Python code and converts it into a nested dictionary.
- While this method works, it is not recommended for untrusted inputs due to security risks.