How can Python convert a string into a dictionary?

In Python, you can use the eval() function to convert a string into a dictionary. The eval() function evaluates the string as a Python expression and returns the result of the evaluation.

Here is an example code for converting a string into a dictionary:

string = '{"name": "John", "age": 30, "city": "New York"}'
dictionary = eval(string)
print(dictionary)

Output result:

{'name': 'John', 'age': 30, 'city': 'New York'}

It is important to note that when using the eval() function to convert a string to a dictionary, the string must comply with Python syntax rules. Additionally, for safety reasons, it is advisable to only use the eval() function on strings from trusted sources. If the string is untrusted or comes from external input, a more secure method of parsing strings should be used, such as the json.loads() function in the json module.

bannerAds