Convert String to a Dictionary in Python

In this article, we will to convert a String representation of a Dictionary to a dictionary using Python Prgramming language. Also we will learn about dictionary.

Table Of Contents

What is a Dictionary and String representation of a Dictionary?

Dictionary in Python is another data structure in which we can store data in key-value pair in a pair of curly braces and separated with commas. In a dictionary keys are always unique and values can be same.

EXAMPLE :

dict1 = {"name" : "MSD", "runs" : 10773}

Whereas, String representation is also a dictionary enclosed in double or single quote. Basically a dictionary inside a string.str() function is used to convert a dict to string representaion of a dict.See an Example below:

EXAMPLE :

dict1 =  {"name" : "MSD" ,"runs" : 10773}

# type() will print the type of dict1 variable which is a dictionary.
print('type of variable dict1 is : ',type(dict1))

# now we will use str() method to convert dict1 
# variable in string representation of dictionary.
dict2 = str(dict1)

# this will print the type of variable dict2
print('type of variable dict2 is : ',type(dict2))

print(dict2)

OUTPUT :

type of variable dict1 is :  <class 'dict'>
type of variable dict2 is :  <class 'str'>
{'name': 'MSD', 'runs': 10773}

Now we know about dict and a string representation of a dictionary. So let’s see the methods through which String representaion of a Dictionary can be converted to a dictionary.

Convert string to dictionary using loads() function

In this method we will use the loads() function of the json module. The json stands for JavaScript Object Notation. This module which comes bundled with python and it is a lightweight data interchange format inspired by JavaScript object literal syntax.

The loads() function recieves one parameter, which is the string representaion of dictionary, that needs to converted to dictionary. It returns a data structure of type dict. Lets see this in an example below :

EXAMPLE :

import json

strValue = '{"name" : "MSD" ,"runs" : 10773}'
# type() will print the data type of variable dict1 which is a string type.
print('data type of strValue is :',type(strValue))

# strValue will be converted to data type dict 
# using json.loads() and will be stored in var dictObj
dictObj = json.loads(strValue)

# type() will print the data type of dictObj.
print('data type of var dictObj is :',type(dictObj))

print(dictObj)

OUTPUT :

data type of strValue is : <class 'str'>
data type of var dictObj is : <class 'dict'>
{'name': 'MSD', 'runs': 10773}

In the code and output above we can see data type of strValue is of type of str and is also a string representaion of a dictionary. Using json.loads() we have successfully converted into dict data type and stored in dictObj variable.In output its clear is of class dict.

Convert string to dictionary using literal_eval()

Next method we will be using to convert String representation of a Dictionary to a dict object, is literal_eval() function of ast module.

The ast stands for Abstract Syntax Trees, which comes bundled with Python programming language. It helps Python applications to process trees of the Python abstract syntax grammar. The literal_eval() function helps to traverse an abstract syntax tree. It recieves one parameter which is node_or_string or the string which needs to be evaluated or which needs to be converted to a dict. Lets see an example below :

EXAMPLE :

import ast

strValue = '{"name" : "MSD" ,"runs" : 10773}'

# type() will print the data type of variable strValue which is a string type.
print('Data type of var strValue : ',type(strValue))

# using ast.literal_eval() function we will convert var strValue which is of str type to dict type.
dictObj =  ast.literal_eval(strValue)

# type() will print the data type of variable dictObj which should be of type dict.
print('Data type of var dictObj : ',type(dictObj))
print(dictObj)

OUTPUT :

Data type of var strValue :  <class 'str'>
Data type of var dictObj :  <class 'dict'>
{'name': 'MSD', 'runs': 10773}

In code and example above you can see how ast.literal_eval() method has been used to convert a String representation of a Dictionary to a dictionary.You can see the data type of var strValue is of type class str which stores string representation of a dictionary and data type of var dictObj is of type class dict.

Convert string to dictionary using eval()

Next method that we will be using is the eval() method. This method works same as the literal_eval() method.

It recieves three parameters :

  • expression : which needs to be evaluated , here the string representaion of the dictionary which needs to be converted to dict.
  • globals : optional , takes a dict
  • locals : optional , takes a mapping object.

SYNTAX :

eval(expression, globals=None, locals=None)

Lets see an Example of the method above :

strValue = ' {"name" : "MSD" ,"runs" : 10773}'

# type() will print the type of strValue 
# variable which is a dictionary.
print('type of variable strValue is : ',type(strValue))

# eval() method has been used to convert a 
# string representation of a dictionary to dict
dictObj = eval(strValue)

# type() will print the type of dictObj 
# variable which is a dictionary.
print('type of var dictObj is :', type(dictObj))

print(dictObj)

OUTPUT :

type of variable strValue is :  <class 'str'>
type of var dictObj is : <class 'dict'>
{'name': 'MSD', 'runs': 10773}

In Example code and output above, you can see the eval() method has been used to convert a String representation of a dict to a dict. You can see var strValue is of type class str. And return of eval() method has been stored in variable dictObj.

Summary

In this article, we learned about dictionary and String representation of dictionary. Also we learned to convert String representation of a dictionary to Dictionary using three different methods. The most useful and easy method can be the eval() method because it has shorter syntax and you don’t need to import any module in your code. Make sure to run these codes in your machine and play with codes. We have used Python 3.10.1 for writing example codes. To check your version write python –version in your terminal.

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top