Convert string to dictionary in PythonWe have worked on different problems based on strings and dictionaries. In this tutorial, we will see how we can convert a string to a dictionary in Python. Before that, let’s have a quick recall of strings and dictionaries. Strings are defined as a sequence of characters and are denoted using single or double inverted commas. For example- We can check the data type of the above variables using type(). Dictionaries are defined as a data structure in Python that uses key-value pairs which are enclosed in curly braces. We can access the values present in the dictionary with the help of respective keys. The example of a dictionary is- Now let’s list out the methods that can convert a string to a dictionary.
It’s time to discuss each one of them in detail- Using json.loads()The following program shows how we can convert a string to a dictionary using json.loads() Output: String_1 is {"subj1":"Computer Science","subj2":"Physics","subj3":"Chemistry","subj4":"Mathematics"} The resultant dictionary is {'subj1': 'Computer Science', 'subj2': 'Physics', 'subj3': 'Chemistry', 'subj4': 'Mathematics'} Explanation: Let’s understand what we have done in the above program-
Using ast.literal_eval()Now we will see how ast.literal_eval can help us to meet our objective. The following program illustrates the same- Output: String_1 is {"subj1":"Computer Science","subj2":"Physics","subj3":"Chemistry","subj4":"Mathematics"} The resultant dictionary is {'subj1': 'Computer Science', 'subj2': 'Physics', 'subj3': 'Chemistry', 'subj4': 'Mathematics'} Explanation: Let’s understand what we have done in the above program-
Using Generator ExpressionsFinally, in the last example we will discuss how generator expressions can be used. Let’s study the given program carefully. Output: String_1 is subj1 - 10 , subj2 - 20, subj3 - 25, subj4 - 14 The resultant dictionary is: {'subj1': 10, 'subj2': 20, 'subj3': 25, 'subj4': 14} <class 'dict'> It’s time to check the explanation of this approach-
ConclusionIn this tutorial, we explored the conversion methods of string to the dictionary. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263404.html