Python | Convert string dictionary to dictionary

Method # 1: Using json.loads()

This task is easy to accomplish using python`s built-in json library load function that converts a valid dictionary string to json form, a dictionary in Python.

# Python3 demo code
# convert a dictionary string to a dictionary
# using json.loads ()

import json

 
# initializing string

test_string = `{" Nikhil ": 1," Akshat ": 2," Akash ": 3}`  

 
# print the original line

print ( "The original string:" + str (test_string))

 
# using json.loads ()
# convert a dictionary string to a dictionary

res = json.loads (test_string)

 
# print result

print ( "The converted dictionary:" + str (res))

Output:

 The original string: {"Nikhil": 1, "Akshat" : 2, "Akash": 3} The dictionary: {`Nikhil`: 1,` Akshat`: 2, `Akash`: 3} 

Method # 2: Using ast.literal_eval ()

The above method can also be used to perform a similar transformation. This function is safer than the eval function and can be used to interconvert all data types except a dictionary.

# Python3 demo code
# convert a dictionary string to a dictionary
# using ast.literal_eval ()

import ast

 
# initialization string

test_string = `{" Nikhil ": 1," Akshat ": 2," Akash ": 3}`  

 
# print the original line

print ( "The original string:" < / code> + str (test_string))

 
# using ast.literal_eval ()
# convert a dictionary string to a dictionary

res = ast.literal_eval (test_string)

 
# print result

print ( "The converted dictionary:" + str (res))

Output:

 The original string: {"Nikhil": 1, "Akshat" : 2, "Akash": 3} The converted dictionary: {`Nikhil`: 1,` Akshat`: 2, `Akash`: 3}