I want to convert the following string into dictionary without using eval()
function in Python 3.5.
d="{'Age': 7, 'Name': 'Manni'}";
Can anybody tell me the good way than using the eval()
function?
What I really want is a function which can directly convert a dictionary to a string.
To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.
Method 4: If the string is itself in the form of string dictionary In this approach, a string which is already in the form of string dictionary i.e., the string has a dictionary expression is converted into a dictionary using ast. literal_eval() method. Below is the implementation of the approach.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
After manipulating both the strings the dictionary items will be created using those key:value pair. Below is the implementation of the approach. In this approach, again 2 strings will be used, one for generating keys and another for generating values for the dictionary.
This task can easily be performed using the inbuilt function of loads of json library of python which converts the string of valid dictionary into json form, dictionary in Python. The above method can also be used to perform a similar conversion.
Sometimes, we are fed with string and we may have to convert it’s content to dictionary. The string may have a specified format that could be key-value convertible. This type of problem is quite common in Machine Learning domain.
In 1st step, the string is converted to list using split and then converted back to dictionary using dictionary comprehension. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With