Python

Python String to a Dict

Strings are used to send/communicate data over the network, but when this string is received by a program, it has to be converted into a data type that supports faster manipulations. In Python, there are dictionaries that allow the user to store data in the form of pairs or key-pair values. These are very similar to JSON, and in this post, you are going to learn how to convert a Python String into a dictionary.

The content of this guide is as follows:

Let’s start with the first method right away.

Method 1: Using the json.loads() Method to Convert String Into Dict

The loads() method is used to “load” a JSON string and convert it into a JSON, or in Python, a Dictionary. However, for this method to work, the string has to be in the specific format in which each “key” is encapsulated by quotation marks, separated by a colon from the “value”. And every pair is separated by a comma.

To demonstrate the working of the loads() method for string-to-dictionary conversion, use the following code snippet:

import json

stringVar = '{"Name":"John Doe", "Age" : "20", "Occupation": "Doctor"}'

resultVar = json.loads(stringVar)
print("Initial String: ",stringVar)
print("After Conversion: ",resultVar)
print("Type After Conversion: ",type(resultVar))

 

In this code snippet:

  • The “json” module is imported so that the user can utilize the loads() method.
  • After that, the string “stringVar” is initialized
  • The loads() method is applied on the stringVar and the result is stored in the “resultVar” variable
  • Lastly, the original string, the resultVar, and the type of the resultVar are printed onto the terminal.

When this code is executed, it produces the following outcome on the terminal:

In this output, you can easily notice that the string has been successfully converted to a dict data type in Python.

Method 2: Using the ast.literal_eval() Method to Convert String Into Dict

The literal_eval() method from the “ast” package can also be used to do exactly the same job as the loads() method from the “json” package. To use this method, take a look at the following code:

import ast

stringVar = '{"Name":"John Doe", "Age" : 20, "Occupation": "Doctor", "Salary" : 40000}'

resultVar = ast.literal_eval(stringVar)
print("Initial String: ",stringVar)
print("After Conversion: ",resultVar)
print("Type After Conversion: ",type(resultVar))

 

When this code is executed, it will produce the following result on the terminal:

The output verifies that the string has been successfully converted into a Python Dict.

Method 3: Using the eval() Method to Convert String Into Dict

Another very similar method is the eval() method which is used to evaluate whether a string is correctly formatted or not and returns the converted dictionary back to the caller. To see its working, take the following code example:

stringVar = '{"Name":"John Doe", "Age" : 20, "Occupation": "Doctor", "Salary" : 40000}'

resultVar = eval(stringVar)
print("Using the eval() Method")
print("Initial String: ",stringVar)
print("After Conversion: ",resultVar)
print("Type After Conversion: ",type(resultVar))

 

When this code is executed, it will produce the following output on the terminal:

You have successfully converted a Python String into a Python dict using the eval() method.

Method 4: Using strip() and split() in Generator Expressions

Suppose that the string is not in the JSON String format, and you still want to convert it into a Python Dict. For this purpose, you would have to utilize various string manipulation methods like strip() and split(). For example, suppose the string contains key-value pairs, in which the key and value are separated by a hyphen “”, and each pair is separated by a comma. For example, this is the string to be converted:

stringVar = "Name - John Doe , Age - 20 , Occupation - Doctor, Martial_Status - Single"

 

To do this, the user can utilize the generator expression, take a look at the following code:

stringVar = "Name - John Doe , Age - 20 , Occupation - Doctor, Martial_Status - Single"

resultVar = dict((a.strip(),b.strip())
    for a,b in (section.split("-")
                for section in stringVar.split(",")))

print("Initial String: ",stringVar)
print("AfterConversion: ",resultVar)
print("Type After Conversion: ",type(resultVar))

 

To understand this code, start from the innermost loop:

  • The string is slit on every occurrence of a comma to get individual key-pairs
  • For every key-pair substring, the string is split on the occurrence of a hyphen “” and the two sections are allotted to variables “a” and “b”. The “a” holds the key part, whereas the “b” holds the value part.
  • The strip() method is applied on both variables “a” and “b” to remove any blank spaces before or after the string.
  • After that, both of these variables are passed into the dict() method to create a new Dictionary variable, “resultVar”
  • Lastly, print the original string and the converted variable resultVar and its type onto the terminal using the print method()

When this code is executed, it produces the following output:

It can be easily observed that the string has been converted into a Python dict.

Conclusion

To convert a string into a Python “dict”, the user can use the loads() method from the “json” package or the literal_eval() method from the “ast” package. However, to use these two methods, the string should be a JSON String. Other than this, if the string is in a different format, then the user will have to use a combination of various string manipulation methods to come up with a working generator expression.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.