Computer >> Computer tutorials >  >> Programming >> Python

Convert string dictionary to dictionary in Python


In this article we'll see how to convert a given dictionary containing strings into a normal dictionary of key value pairs.

With json.loads

The json.loads can pass a given string and give us the result as normal strings preserving the structure of the data. So we pass the given string dictionary into this function as a parameter and get our result.

Example

import json
stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}'
# Given string dictionary
print("Given string : \n",stringA)
# using json.loads()
res = json.loads(stringA)
# Result
print("The converted dictionary : \n",res)

Output

Running the above code gives us the following result −

Given string :
{"Mon" : 3, "Wed" : 5, "Fri" : 7}
The converted dictionary :
{'Mon': 3, 'Wed': 5, 'Fri': 7}

With ast.literal_eval

This method from ast module works similar to the above approach. The dictionary containing string gets parsed as normal values and produces the normal dictionary.

Example

import ast
stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}'
# Given string dictionary
print("Given string : \n",stringA)
# using json.loads()
res = ast.literal_eval(stringA)
# Result
print("The converted dictionary : \n",res)

Output

Running the above code gives us the following result −

Given string :
{"Mon" : 3, "Wed" : 5, "Fri" : 7}
The converted dictionary :
{'Fri': 7, 'Mon': 3, 'Wed': 5}