AppDividend
Latest Code Tutorials

How to Convert Python String to Dictionary

In Python development, converting one data type to another is a frequent problem, and you must deal with it appropriately. Python dictionary is a robust data structure that deals with key-value pairs. However, when exchanging the data between client and server, json string is used. JSON is a standard for data exchange, and when data is available on the client-side, we need to convert the json string to a dictionary. To convert a Python string to a dictionary, continue this article.

Python string to dict

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. The json.loads() function takes a json string as argument and returns the dictionary.

First, let’s define a json string.

str = '{"Name": "Millie", "Age": 18, "City": "Atlanata"}'

print('The JSON String is', str)

Output

The JSON String is {"Name": "Millie", "Age": 18, "City": "Atlanata"}

Let’s use the json.loads() method to convert a string into a dictionary.

Before you use the loads() method, import json package in your program.

import json

Now, you can use the loads() method.

# app.py

import json

str = '{"Name": "Millie", "Age": 18, "City": "Atlanata"}'

print('The JSON String is', str)

convertedDict = json.loads(str)

print("After conversion: ", convertedDict)
print(type(convertedDict))

Output

The JSON String is {"Name": "Millie", "Age": 18, "City": "Atlanata"}
After conversion:  {'Name': 'Millie', 'Age': 18, 'City': 'Atlanata'}
<class 'dict'>

You can see that the loads() function returns a dictionary, and we verified that using the type() method.

To convert Python dict to string, use the json.dumps() method.

This is the first and easy way to convert string to dict in Python. Let’s see another way.

Using ast.literal_eval()

The ast.literal_eval() is a built-in Python library function used to convert string to dict. To use literal_eval() function, import the ast package and use its literal_eval() method.

# app.py

import ast

str = '{"Name": "Millie", "Age": 18, "City": "Atlanata"}'

print('The JSON String is', str)

convertedDict = ast.literal_eval(str)

print("After conversion: ", convertedDict)
print(type(convertedDict))

Output

The JSON String is {"Name": "Millie", "Age": 18, "City": "Atlanata"}
After conversion:  {'Name': 'Millie', 'Age': 18, 'City': 'Atlanata'}
<class 'dict'>

You can see that the output is the same as the loads() function, and it does the same thing.

Using generator expressions in Python

If we have enough strings to form a dictionary, then we can use the generator expressions to convert the string to a dictionary.

# app.py

str = "E - 11, K - 19, L - 21"

convertedDict = dict((x.strip(), int(y.strip()))
                     for x, y in (element.split('-')
                                  for element in str.split(', ')))

print("Converted dict is: ", convertedDict)
print(type(convertedDict))

Output

Converted dict is:  {'E': '11', 'K': '19', 'L': '21'}
<class 'dict'>

In this example, we have used many Python functions like dict(), strip(), int()and split().

First, we split the string inside the for loop and convert them into a dictionary using the dict() method. Next, the strip() method is used to remove whitespace from the string and use the int() function to convert string to int for integer values.

Conclusion

The json package is helpful when dealing with json data. It can help you convert the Python object to json object and json object to Python object easily. That is it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.