3 Simple Ways to Convert Dictionary to String Python With Ease in 2023

Finding it difficult to convert dictionary to string Python? If yes, then have a close look at the 2 simple ways to convert dictionary to string Python.

From lists and tuples to dictionaries and strings, python has many different data types that are very well suited for some tasks specific to them.

But as we program real-world applications, we come to know that in order to use their full potential, we must know how to convert one data type to another.

In this article, we will discuss how to convert dictionary to string Python.

What is Dictionary?

A dictionary is a data structure which contains a collection of key-value pairs. The basic syntax of a python dictionary is:

dictionary_name = {‘key1’ : ‘value1’, ‘key2’ : ‘value2’…}

Dictionaries can store different types of values for keys and inputs, even different keys or values can also have different data types. We can access a value in a dictionary by the corresponding key value.

Note: keys and values both in dictionaries are case-sensitive i.e., uppercase and lowercase letters are treated differently.

Example:

dict = {‘movieName’:’Free Guy’, ‘rating’:’7.1′, ‘lang’:’en’}

print(dict)

Output:

{‘movieName’: ‘Free Guy’, ‘rating’: ‘7.1’, ‘lang’: ‘en’}

What are Strings?

Strings in python are collection of characters arranged in a sequential manner. Characters are the symbols that we type from keyboard. @, #, e, 1, 2 are all characters and can be part of a string.

There is a property of strings that we need to know, that is, Strings are immutable, meaning once defined, their value cannot be altered. When we perform any string medication like using the join() method, the method returns a different string with the necessary changes, not the original string.

See also  Top 5 Easiest Programming Languages To Learn in 2023

Example:

str = ‘this is a string’

print(str)

Output:

this is a string

Understanding Problem Statement

The task that we need to perform is itself not very complicated. Basically, we are given a dictionary in its normal syntax (inside curly braces) and we need to convert it to a string enclosed in quotation marks (“”). For example:

dict = {‘key1′:’value1’, ‘key2′:’value2’, ‘key3′:’value3’}

print(f”Dictionary before conversion : {dict}”)

str = ‘key1 : value1, key2 : value2, key3 : value3’

print(f”String after conversion : {str}”)

Output:

Dictionary before conversion : {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

String after conversion : key1 : value1, key2 : value2, key3 : value3

Confirming Dictionary to String Conversion

Once we have converted the dictionary into string, how do we actually check if it has actually been converted or not. Well, a simple solution to this problem would be to use the type() method, which tells us the type of an object.

Another way to do it is to try and check the value using a key in the initial dictionary. If the object returns a single character, it is a string, otherwise it is a dictionary. This isn’t as reliable as the type() method but can be used to check the difference.

Example:

dict = {‘key1′:’value1’, ‘key2′:’value2’, ‘key3′:’value3’}

print(f”dictionary before conversion : {dict}”)

print(f”Type of dictionary : {type(dict)}”)

str = ‘key1 : value1, key2 : value2, key3 : value3’

print(f”String after conversion : {str}”)

print(f”Type of string : {type(str)}”)

Output:

dictionary before conversion : {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

Type of dictionary : <class ‘dict’>

String after conversion : key1 : value1, key2 : value2, key3 : value3

Type of string : <class ‘str’>

You May Also Like

How to Reverse An Array Python? 5 Easy Steps to Follow 2023

See also  Top 7 Interesting Uses Of JavaScript: One should know in 2022

How to Convert Dictionaries to Strings ?

Now we come to the most important part, how to convert dictionary to string Python. We will discuss 3 best methods.

Iterative Method

The iterative method seems the most conventional way to do this conversion. We can iterate over a dictionary for the key and value elements, and keep concatenating them into a blank string to get the conversion. The steps to followed are : 

  • Initialise a blank string(“”)
  • Iterate over the dictionary for every key-value pair
  •  Add the key , then ‘:’ and then value for every pair

Example:

dict = {‘key1′:’value1’, ‘key2′:’value2’, ‘key3′:’value3’}

print(f”Dictionary before conversion : {dict}”)

# initialise a blank string

str = ”

# store the length of the dictionary, this will stop us from putting ‘,’ at the end of the string

len = len(dict)

i = 0

# traverse the dictionary

for key in dict:

    # add the key value pair in the string

    str = str + key + ‘:’ + dict[key]

    i += 1

    # we add a ‘,’ for every iteration, except the last one

    if(i<len):

        str = str + ‘, ‘

print(f”String after conversion : {str}”)

Output:

Dictionary before conversion : {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

String after conversion : key1:value1, key2:value2, key3:value3

str() function

The str() function is an inbuilt function that provides a string variant of an object (dictionary in our case). It takes the object as a parameter and returns the string equivalent of the dictionary. The original object is not changed in this method.

Example:

dict = {‘key1′:’value1’, ‘key2′:’value2’, ‘key3′:’value3’}

print(f”dictionary before conversion : {dict}”)

print(f”Type of dictionary : {type(dict)}”)

# using str() method

str = str(dict)

print(f”String after conversion : {str}”)

See also  Python Vs Java - Which One Is Better To Choose?

print(f”Type of string : {type(str)}”)

Output:

 dictionary before conversion : {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

Type of dictionary : <class ‘dict’>

String after conversion : {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

Type of string : <class ‘str’>

You may notice that the resultant string still has curly braces in it. This is because the string method converts the whole set characters into a string as it is, therefore care must be taken in such cases

json.dumps() function

The dumps() method from the JSON library can also be used for converting dictionary to string. Give the dumps() method a JSON object and we get a string equivalent of that object, without changing the object. This method requires to import the JSON library for its usage. 

Example:

# import the dumps method from json library

from json import dumps

dict = {‘key1′:’value1’, ‘key2′:’value2’, ‘key3′:’value3’}

print(f”dictionary before conversion : {dict}”)

print(f”Type of dictionary : {type(dict)}”)

# using dumps() method

str = dumps(dict)

print(f”String after conversion : {str}”)

print(f”Type of string : {type(str)}”)

Output:

 dictionary before conversion : {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

Type of dictionary : <class ‘dict’>

String after conversion : {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

Type of string : <class ‘str’>

Conclusion

This is all about convert dictionary to string Python. The conversion of a dictionary to a string is a very important concept to learn. Dictionaries, which are good for mapping data in a key-value fashion serve their purpose well.

But when it comes to storage and parsing the data, strings are the norm. JSON, which is a form of data suited for transportation of information, uses strings.

Therefore it is important to learn to convert dictionary to string Python in order to use the best parts of both the data structures and increasing the efficiency of the program. If you think that we have missed any method to dictionary to string Python then comment down below.

Leave a Comment

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