Open In App

Python – Convert dictionary object into string

Last Updated : 21 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Python, there are situations where we need to convert a dictionary into a string format.
For example, given the dictionary {‘a’ : 1, ‘b’ : 2} the objective is to convert it into a string like “{‘a’ : 1, ‘b’ : 2}”. Let’s discuss different methods to achieve this:

Using str

The simplest way to convert a dictionary to a string is by using the built-in function for string conversion.

# Input dictionary
a = {'a': 1, 'b': 2}

# Converting dictionary to string
b = str(a)

print(b)

Output
{'a': 1, 'b': 2}

Explanation:

  • str function converts the dictionary into its string representation.
  • It is straightforward and efficient, suitable for general purposes.

Let’s explore some more ways and see how we can convert dictionary object into string.

Using json.dumps

Another method is to use the dumps function from the json module for converting a dictionary into a JSON-formatted string.

import json

# Input dictionary
a = {'a': 1, 'b': 2}

# Converting dictionary to JSON string
b = json.dumps(a)

print(b)

Output
{"a": 1, "b": 2}

Explanation:

  • json.dumps converts the dictionary to a string following JSON format, useful when working with APIs or web applications.
  • It adds double quotes around keys and values if they are string values for JSON formatting.

Using repr

This method uses repr() function and converts the dictionary into a string representation that can be evaluated back into a dictionary.

# Input dictionary
a = {'a': 1, 'b': 2}

# Converting dictionary to string using repr
b = repr(a)

print(b)

Output
{'a': 1, 'b': 2}

Explanation:

  • repr() function produces a detailed string representation of the dictionary similar to str.
  • Useful when we need the output as a valid Python expression.

Using String Concatenation

This method manually constructs the string representation of the dictionary by concatenating its key-value pairs.

# Input dictionary
a = {'a': 1, 'b': 2}

# Converting dictionary to string manually
b = "{" + ", ".join(f"'{k}': {v}" for k, v in a.items()) + "}"

print(b)

Output
{'a': 1, 'b': 2}

Explanation:

  • join() function Joins key-value pairs as strings to create a custom output format.
  • This method offers flexibility in creating custom formats but is less efficient than built-in functions.


Next Article

Similar Reads

three90RightbarBannerImg