How to Convert Dict to String Python

In this Python tutorial, I will show you how to convert a dict to a string Python.

While creating a web application using Python, I needed to send the data in a dictionary over the network, but we couldn’t send the dictionary objects over the network.

So I needed a way to convert the dictionary into a format that is sendable over the network, and there was a solution that was converting the dict string into json string.

I used the dumps() method from the Python JSON module and converted the dictionary objects into strings.

In this tutorial, I have explained how I converted the dictionary into a string using the dumps() function and shared two additional approaches that you can use to convert the dictionary into a string.

Let’s begin,

Convert Dict to String Python

There are three approaches that you can use to convert the dict to string in Python, first using the json module, second using the str() function and third using the print method.

Head to the following section to learn how to use these methods to convert the given dictionary into a string.

Convert Dict to String Python using json Module

The json module has a function called dumps() which converts the given Python objects into json strings. So here you will convert the Python dictionary objects into json strig.

The syntax is given below.

json.dumps(python_objects)

Where,

  • json.dumps(): This function accepts the Python object you want to convert into a string.
READ:  How to Set Background to be an Image in Python Tkinter

Let’s take an example where a dictionary named movies contains the movie name and its directory and casts, as shown below.

movies = {
    "The Shawshank Redemption": {
        "director": "Frank Darabont",
        "cast": ["Tim Robbins", "Morgan Freeman", "Bob Gunton"]
    },
    "The Godfather": {
        "director": "Francis Ford Coppola",
        "cast": ["Marlon Brando", "Al Pacino", "James Caan"]
    },
    "Inception": {
        "director": "Christopher Nolan",
        "cast": ["Leonardo DiCaprio", "Joseph Gordon-Levitt", "Ellen Page"]
    },
    "Forrest Gump": {
        "director": "Robert Zemeckis",
        "cast": ["Tom Hanks", "Robin Wright", "Gary Sinise"]
    },
}

To convert the above dictionary into a string, you can use the json.dumps() function, as shown in the code below.

import json

dict_str = json.dumps(movies)
Convert Dict to String Python using json Module

From the output, you can see when the dictionary named movies is passed to the dumps() function like json.dumps(movies), it creates a string of that dictionary and stores that string into a new variable named dict_str.

As a result, it returns a string like this {“The Shawshank Redemption”: {“director”: “Frank Darabont”, “cast”: [“Tim Robbins”, “Morgan Freeman”, “Bob Gunton”]}}.

Similarly, using the json.dumps() function, you can convert any dict into a string.

Convert Dict to String Python using str() Method

The str() function in Python is a built-in function that takes any value and converts it into a string, or it can convert the data type of any value into a string.

The syntax is given below.

str(value)

Where,

  • str(value): This function accepts a value that you want to convert into a string.

Let’s see, for example, suppose you have a dictionary named programming_languages, as shown below.

programming_languages = {
    "Python": {
        "designed_by": "Guido van Rossum",
        "year_created": 1991,
        "popularity_rank": 1
    },
    "JavaScript": {
        "designed_by": "Brendan Eich",
        "year_created": 1995,
        "popularity_rank": 2
    },
    "Java": {
        "designed_by": "James Gosling",
        "year_created": 1995,
        "popularity_rank": 3
    },
    "C++": {
        "designed_by": "Bjarne Stroustrup",
        "year_created": 1985,
        "popularity_rank": 4
    },
    "Swift": {
        "designed_by": "Apple Inc.",
        "year_created": 2014,
        "popularity_rank": 5
    },
}

The code below converts the above dictionary into a string using the str() function.

dictionary_str = str(programming_languages)
print ("\n", type(dictionary_str))
print (dictionary_str)
Convert Dict to String Python using str() Method

Look at the above output; the dictionary named programming_language is converted into a string.

READ:  Login system in Python Django

Let’s understand the code part, dictionary_str = str(programming_languages). This line of code takes the dictionary programming_language and converts it into the string using the str() method. Then, it stores the converted dict in the dictionary_str variable.

After that, this line of code print (“\n”, type(dictionary_str)) prints the type of the variable dictionary_str using the type() function. If you look at the output in the above picture, it returns the type as <class ‘str’>, indicating that it is a string.

Finally, print the string using the print (dictionary_str), which shows {‘Python’: {‘designed_by’: ‘Guido van Rossum’, ‘year_created’: 1991, ‘popularity_rank’: 1}} on the terminal.

This is how to convert the dictionary into the string using the str() function.

Python Convert Dict to String using the print() Method

The print() method allows you to customally format the string or use the concept of string interpolation.

Let’s see with an example, suppose you have a dictionary named data_analysis as shown below.

data_analysis = {
    "data_cleaning": {
        "tools_used": ["pandas", "NumPy"],
        "benefits": [
            "Improves data accuracy and reliability",
            "Ensures consistency in analysis results"
        ]
    },
    "data_visualization": {
        "tools_used": ["matplotlib", "seaborn", "Plotly"],
        "benefits": [
            "Enhances understanding of complex datasets",
            "Facilitates communication of findings"
        ]
    },
    "statistical_analysis": {
        "tools_used": ["SciPy", "statsmodels"],
        "benefits": [
            "Quantifies uncertainty and variability in data",
            "Provides evidence for hypotheses"
        ]
    }
}

To convert the above dictionary into a string, you can use the print() method, as shown below.

print(f"\n{data_analysis}")
Python Convert Dict to String using the print() Method

From the output, you can see the print() method converted the given dictionary into a string as a result it returns the string like this {‘data_cleaning’: {‘tools_used’: [‘pandas’, ‘NumPy’], ‘benefits’: [‘Improves data accuracy and reliability’, ‘Ensures consistency in analysis results’]}.

READ:  How to Create a List of Tuples in Python [6 Methods + Examples]

This is how to convert the given dict to string in Python using the print() method by applying the concept of string interpolation.

Conclusion

In this Python tutorial, you learned how to convert a dict to a string Python. You learned how to use the dumps() function of the json module to convert the dictionary object into a json string, then used the str() method to convert the dict to a string.

Finally, the print() method was used to convert the dictionary into a string using string interpolation.

You may like to read: