How to Convert String to Dictionary in Python

To convert a string to a dictionary in Python, you can use the json.loads() function from the json module if the string is in a JSON-compliant format. The json.loads() function takes a json string as an argument and returns the dictionary.

Example

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.

If the string is not in JSON format, you may need to parse it manually or use a custom parsing function depending on the specific format of the string.

Alternate methods

Using ast.literal_eval() function

The ast.literal_eval() is a built-in Python library function that converts a string to a dict.

To use the literal_eval() function, import the ast package and use its literal_eval() method.

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, use the generator expressions to convert the string to a dictionary.

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 converted them into a dictionary using the dict() method.

Next, the strip() method removes whitespace from the string and uses the int() function to convert the string to int for integer values.

FAQ

How to convert a string to a dictionary in Python?

You can convert a string to a dictionary in Python using the json module’s loads() function.

import json

string = '{"key1": "value1", "key2": "value2"}'
dict = json.loads(string)
print(dict)

Can I convert a dictionary to a string in Python?

Yes, you can convert a dictionary to a string in Python using the json module’s dumps() function.

Can I convert a dictionary to a string in a specific format?

Yes, you can convert a dictionary to a string in a specific format by manually looping through the dictionary and constructing the string according to the desired format.

import json

dict = {"key_first": "value_first", "key_second": "value_second"}
string = ','.join(['{}:{}'.format(key, value) for key, value in dict.items()])
print(string)

Output

key_first:value_first,key_second:value_second

Conclusion

The easiest way is to use the json.loads() function to convert a valid string to a dict in Python.

Further reading

Python string to list

Python string to list of characters

Python string to array

Python string to dict

Python string to hex

Leave a Comment

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