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.

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'>

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'>

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'>

Conclusion

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

Related posts

Python string to list

Python string to array

Python string to dict

Python string to hex

1 thought on “How to Convert String to Dictionary in Python”

  1. Hi,
    thank you !
    i have an other expression to convert to dict like this :
    can you help me please?
    resu = {
    “list_file”:”{

    \”iross\”: [
    \”artt\”,
    \”artction\”,
    \”artiong\”,
    \”artiype\”,
    \”coon\”,
    \”colleong\”,
    \”collype\”,
    \”genre\”,
    \”genst\”,
    \”genction\”,
    \”rle\”,
    \”sog\”,
    \”storont\”,
    \”mepe\”,
    ],
    \”mch\”: [\”mach\”, \”coltch\”, \”stch\”],
    \”popularity\”: [\”album_poe\”, \”song_populanre\”]
    }”}

    Reply

Leave a Comment

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