ID : 48
viewed : 124
Tags : PythonPython StringPython Dictionary
97
A dictionary in Python is an ordered collection of data values stored in a key: value pair. It can be created by placing elements within curly braces and separating them by a comma. A string in Python is a sequence of Unicode characters. It can be created by enclosing characters in single quotes or double-quotes.
In this tutorial, we will discuss how to convert a dictionary to a string and back in Python.
json
Module to Convert a Dictionary to a String and Back in Pythonjson
is an acronym for JavaScript Object Notation
. This module produces the output in plain text only. It also supports cross-platform and cross-version.
For example,
import json dict = {'Hello': 60} s = json.dumps(dict) print(s) d = json.loads(s) print(d)
Output:
{"Hello": 60} {'Hello': 60}
The function json.dumps()
extracts data from the json object passed as a parameter and returns it in the form of a string. The function json.loads()
takes in a string as a parameter and returns a json object.
str()
and the literal_eval()
Function From the ast
Library to Convert a Dictionary to a String and Back in PythonThis method can be used if the dictionary’s length is not too big. The str()
method of Python is used to convert a dictionary to its string representation. The literal_eval()
from ast
library is used to convert a string to a dictionary in Python.
For example,
import ast dict = {'Hello': 60} str(dict) ast.literal_eval(str(dict))
Output:
"{'Hello': 60}" {'Hello': 60}
pickle
Module to Convert a Dictionary to a String and Back in PythonThe dumps()
function from the pickle
module is used to convert a dictionary into a byte stream in Python. The loads()
function does the opposite i.e. it is used to convert the byte stream back into a dictionary in Python.
For example,
import pickle dict = {'Hello': 60, 'World': 100} s = pickle.dumps(dict) print(s) d = pickle.loads(s) print(d)
Output:
b'\x80\x04\x95\x19\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05Hello\x94K<\x8c\x05World\x94Kdu.' {'Hello': 60, 'World': 100}