Change language

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} 

Python | Convert string dictionary to dictionary __dict__: Questions

Python | Convert string dictionary to dictionary Python functions: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method