The Wayback Machine - https://web.archive.org/web/20240905163208/https://www.geeksforgeeks.org/python-convert-dictionary-object-into-string/
Open In App

Python | Convert dictionary object into string

Last Updated : 04 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it’s necessary to learn about them. 

Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}
Output: {"testname": "akshat", "test2name": "manjeet", "test3name": "nikhil"}
Explanation: Input type is <class 'dict'> but the output type is <class 'str'>

Let’s see the different ways of changing a dictionary into a string.

Dictionary object into string Conversation

Below are the methods that we will cover in this article:

Converting Dict to String in Python using json.dumps() method

Here we can use the dump() method from the JSON library by importing it which converts the dictionary data type to string. In the below code, we first take a dictionary test1 then we use json.dumps method and pass the tes1 dictionary in it and we will get the required result in the string format.

Python3




import json
 
# initialising dictionary
test1 = { "testname" : "akshat",
          "test2name" : "manjeet",
          "test3name" : "nikhil"}
 
# print original dictionary
print (type(test1))
print ("initial dictionary = ", test1)
 
# convert dictionary into string
result = json.dumps(test1)
 
# printing result as string
print ("\n", type(result))
print ("final string = ", result)


Output:

initial dictionary = {‘testname’: ‘akshat’, ‘test2name’: ‘manjeet’, ‘test3name’: ‘nikhil’}
final string = {“testname”: “akshat”, “test2name”: “manjeet”, “test3name”: “nikhil”}

Space complexity : O(n)
Time complexity : O(n)

Dictionary into string conversion using str() function

The str() function converts the specified value into a string. The string function is also helpful to convert the data type into string type by this we pass the dictionary into this method and it will convert the datatype form dictionary to string datatype.

Python3




test1 = { "testname" : "akshat",
          "test2name" : "manjeet",
          "test3name" : "nikhil"}
 
# print original dictionary
print (type(test1))
print ("initial dictionary = ", test1)
 
# convert dictionary into string
result = str(test1)
 
# print resulting string
print ("\n", type(result))
print ("final string = ", result)


Output:

initial dictionary = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’} 
final string = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’}

Space complexity : O(n)
Time complexity : O(n)

Convert dictionary into string using print method

Another approach to convert a dictionary object into a string is to use the print. The print provides a way to pretty-print arbitrary Python data structures in a form that print can be used as input to the interpreter.

Here is an example of using the print that module to convert a dictionary object into a string:

Python3




import pprint
 
# Initialize dictionary
d = { "testname" : "akshat", "test2name" : "manjeet", "test3name" : "nikhil" }
 
# Print original dictionary
print(f"Original dictionary: {d}")
 
# Convert dictionary into string using pprint.pformat()
result = pprint.pformat(d)
 
# Print resulting string
print(f"\nResulting string: {result}")
print("Type is: ",type(result))


Output

Original dictionary: {'testname': 'akshat', 'test2name': 'manjeet', 'test3name': 'nikhil'}

Resulting string: {'test2name': 'manjeet', 'test3name': 'nikhil', 'testname': 'akshat'}
Type is:  <class 'st...

Space complexity : O(n)
Time complexity : O(n)

The print module provides more control over the formatting of the resulting string, such as indentation and line width, than the built-in str and json.dumps functions.



Similar Reads

How to convert Python's .isoformat() string back into datetime object
In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable. The function now() of this module, does the job perfectly. Example: Getting current time C/C++ Code from datetime import datetime current
1 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
How To Convert Generator Object To Dictionary In Python
Generators in Python are powerful constructs for handling large datasets efficiently. However, there may be scenarios where you want to convert the output of a generator into a dictionary for easier manipulation and retrieval of data. In this article, we'll explore five different methods to convert a generator object to a dictionary in Python. Conv
3 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition. Below are some ways to achieve the above task. I
8 min read
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictionary into Pandas DataframeBelow are the methods th
4 min read
Python | Convert two lists into a dictionary
Interconversion between data types is usually necessary for real-time applications as certain systems have certain modules that require input in a particular data type. Let's discuss a simple yet useful utility of conversion of two lists into a key: value pair dictionary in Python. Converting Two Lists into a DictionaryPython List is a sequence dat
11 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
How to convert a dictionary into a NumPy array?
It's sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a dictionary into NumPy array but before applying th
3 min read
Convert Unicode String to Dictionary in Python
Python's versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is converting it into a dictionary. In this article, we will
2 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Convert Object to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting an object to a string. Converting Object to String Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods. Example 1: Using str(
1 min read
How to convert timestamp string to datetime object in Python?
Python has a module named Datetime to work with dates and times. We did not need to install it separately. It is pre-installed with the Python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC. Input: "2023-07-21 10:30:45"Output: 2023-07-21 10:30:45Explanation: In This, We are converting a tim
2 min read
Ways to convert string to dictionary
Dictionary is an unordered collection in Python that store data values like a map i.e., key: value pair. In order to convert a String into a dictionary, the stored string must be in such a way that key: value pair can be generated from it. This article demonstrates several ways of converting a string into a dictionary. Method 1: Splitting a string
4 min read
How to convert categorical string data into numeric in Python?
The datasets have both numerical and categorical features. Categorical features refer to string data types and can be easily understood by human beings. However, machines cannot interpret the categorical data directly. Therefore, the categorical data must be converted into numerical data for further processing. There are many ways to convert catego
4 min read
Convert String into Variable Name in Python
There may be situations where you want to convert a string into a variable name dynamically. In this article, we'll explore how to convert a string into a variable name in Python with four simple examples. Convert String into Variable Name in PythonWhile Python does not directly allow you to convert a string into a variable name, these examples dem
3 min read
Python | Convert a list of characters into a string
Given a list of characters, merge all of them into a string. Examples: Input : ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] Output : geeksforgeeks Input : ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g'] Output : programming Recommended PracticeConvert a list of characters into a StringTry It! Initialize an empty string
3 min read
Turning a Dictionary into XML in Python
XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elements in an XML are contained in an outermost element
3 min read
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Python program to convert XML to Dictionary
In this article, we will discuss how to convert an XML to a dictionary using Python. Modules Usedxmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module. Syntax: pip install xmltodict pprint: The pprint module provides a capability to “pretty
2 min read
Different ways to convert a Python dictionary to a NumPy array
In this article, we will see Different ways to convert a python dictionary into a Numpy array using NumPy library. It’s sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs of t
3 min read
How to convert NumPy array to dictionary in Python?
The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is k
3 min read
Convert PySpark DataFrame to Dictionary in Python
In this article, we are going to see how to convert the PySpark data frame to the dictionary, where keys are column names and values are column values. Before starting, we will create a sample Dataframe: C/C++ Code # Importing necessary libraries from pyspark.sql import SparkSession # Create a spark session spark = SparkSession.builder.appName('DF_
3 min read
Convert Python Dictionary List to PySpark DataFrame
In this article, we will discuss how to convert Python Dictionary List to Pyspark DataFrame. It can be done in these ways: Using Infer schema.Using Explicit schemaUsing SQL Expression Method 1: Infer schema from the dictionary We will pass the dictionary directly to the createDataFrame() method. Syntax: spark.createDataFrame(data) Example: Python c
3 min read
How to convert a MultiDict to nested dictionary using Python
A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested dictionary, where each key corresponds to a diction
3 min read
Python - Convert Lists to Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert lists to nestings, i.e. each list value represents a new nested level. This kind of problem can have applications in many domains including web development. Let's discuss the certain way in which this task can be performed. Convert Lists to Nested D
5 min read
Convert JSON to dictionary in Python
JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the Python JSON package into Python script. The text in JSON is done through quoted-
4 min read
How To Convert Python Dictionary To JSON?
JSON stands for JavaScript Object Notation. It means that a script (executable) file made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which conta
7 min read
Python __iter__() and __next__() | Converting an object into an iterator
In many cases, we may need to access an object in a way that treats it as if it were an iterator. This means we want to interact with the object in a manner similar to how we would with an iterator, enabling us to iterate over it or perform other iterable operations. For clarity, it's useful to say " We need to access an object and make it iterable
6 min read
How to Change a Dictionary Into a Class?
Working with Dictionary is a good thing but when we get a lot of dictionaries then it gets tough to use. So let's understand how we can convert a dictionary into a class. Approach Let's take a simple dictionary "my_dict" which has the Name, Rank, and Subject as my Keys and they have the corresponding values as Geeks, 1223, Python. We are calling a
2 min read