AppDividend
Latest Code Tutorials

How to Convert Python String to Dictionary

0

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. When we are exchanging the data between client and server, json string is used. JSON is a standard for data exchange, and when data available on the client-side, we need to convert the json string to a dictionary.

To convert Python dict to string, use the json.dumps() method. To convert Python string to dictionary, continue this article.

Python String to Dictionary

To convert Python string to a dictionary, use json.loads() method. The json.loads() is an inbuilt Python library function that converts a valid string into a dict.

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"}

To convert JSON String to dict, use json.loads() method.

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.

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 an inbuilt Python library function used to convert string to dict.

Let’s use the above example and 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. 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.