Skip to content

How to Convert Dictionary to String Python? Malli Spark By {Examples}

  • by

How to convert a dictionary to a string in Python? You can convert a dictionary to a string using various methods of Python. One common approach is to use the json module to serialize the dictionary into a JSON-formatted string. The process of converting dictionaries to strings involves serialization, which means transforming data into a format that can be easily stored or transmitted. Python’s json module is commonly used for converting between dictionaries and JSON-formatted strings, as JSON is a widely used data interchange format.

You can convert a dictionary to a string in Python using many ways, for example, by using json.dumps(), str(), print(), empty string & for loop, and for loop & items() functions. In this article, I will explain how to convert a dictionary to a string by using all these functions with examples.

1. Quick Examples of Converting Dictionary to String

If you are in a hurry, below are some quick examples of converting a dictionary to a string.

# Quick examples of converting dictionary to string

import json

# Initializing dictionary
my_dict = {‘course’:’python’, ‘tutor’:’Richerd’, ‘duration’:’45 days’}

# Example 1: Using json.dumps() method
# Converting dictionary to string
result = json.dumps(my_dict)

# Example 2: Using str() method
# Converting dictionary to string
result = str(my_dict)

# Example 3: Using print() method
# Converting dictionary to string
result = pprint.pformat(my_dict)

# Example 4: Using an empty string and for loop
# Convert dictionary to string
converted = str()
for key in my_dict:
converted += key + “: ” + my_dict[key] + “, “
converted = converted.rstrip(‘, ‘)

# Example 5: Convert the dictionary to a string
# Using for loop and items() function
converted = “”
for key, value in my_dict.items():
converted += f”{key}: {value}, “
converted = converted.rstrip(‘, ‘)

2. Convert Dictionary to String Using json.dumps() Method

You can convert a Python dictionary into a JSON-formatted string using the json.dumps() method. For example, first import the json module, which provides functions to work with JSON data. Create a dictionary named my_dict with three key-value pairs. Print the original dictionary my_dict and its data type using the print() function and type() function.

Use the json.dumps() method to convert the dictionary into a JSON-formatted string. This method takes an object as an argument and returns a string representing the object in JSON format. Print the JSON-formatted string stored in the result variable and its data type.

import json

# Initializing dictionary
my_dict = {‘course’:’python’, ‘tutor’:’Richerd’, ‘duration’:’45 days’}
print(“Original dictionary:”,my_dict)
print (“Type of given dictionary:”, type(my_dict))

# Using json.dumps() method
# Converting dictionary to string
result = json.dumps(my_dict)
print(“After converting the dictionary to a string:n”,result)
print(“Type of the converted string:”, type(result))

Yields below output.

As you can see, the dictionary is converted into a JSON-formatted string, which is surrounded by curly braces {} and contains the key-value pairs in double quotes with colons between the keys and values. The resulting string is of type str. This is a common format used for data exchange between systems that can understand JSON.

3. Convert Dictionary to String Using the str() Function

You can also use the str() method to convert a dictionary to a string. For example, first, you initialize a dictionary named my_dict with three key-value pairs. You can pass dictionaryinto this function, it will return the string representation. This representation will retain the curly braces and key-value pairs, but it won’t produce a JSON-formatted string. Print the resulting string stored in the result variable and its data type using the print() function and type() function.

The resulting string retains the dictionary’s curly braces and key-value pairs. However, it’s important to note that this string representation is not in JSON format. If you need JSON format, you should use the json.dumps() method shown in your original example.

# Initializing dictionary
my_dict = {‘course’:’python’, ‘tutor’:’Richerd’, ‘duration’:’45 days’}
print(“Original dictionary:”,my_dict)
print (“Type of given dictionary:”, type(my_dict))

# Using str() method
# Converting dictionary to string
result = str(my_dict)
print(“After converting the dictionary to a string:n”,result)
print(“Type of the converted string:”, type(result))

Yields below output.

4. Convert Dictionary into String Using print() Method

You can use pprint.pformat() function from the pprint module to convert the dictionary into a string. This approach will provide a formatted string representation of the dictionary, making it more readable and suitable for output, but it’s still not in JSON format. You import the pprint module, which provides pretty-printing capabilities to display complex data structures in a more readable manner.

In the below example, first, initialize a dictionary named my_dict with three key-value pairs. Use the pprint.pformat() function to convert the dictionary into a formatted string. Print the resulting formatted string stored in the result variable and its data type using the print() function and type() function.

import pprint

# Initializing dictionary
my_dict = {‘course’:’python’, ‘tutor’:’Richerd’, ‘duration’:’45 days’}
print(“Original dictionary:”,my_dict)
print (“Type of given dictionary:”, type(my_dict))

# Using print() method
# Converting dictionary to string
result = pprint.pformat(my_dict)
print(“After converting the dictionary to a string:n”,result)
print(“Type of the converted string:”, type(result))

# Output:
# Original dictionary: {‘course’: ‘python’, ‘tutor’: ‘Richerd’, ‘duration’: ’45 days’}
# Type of given dictionary: <class ‘dict’>
# After converting the dictionary to a string:
# {‘course’: ‘python’, ‘tutor’: ‘Richerd’, ‘duration’: ’45 days’}
# Type of the converted string: <class ‘str’>

5. Using an Empty String and For Loop

Alternatively, you can use for loop over the given dictionary to convert it into a string. First, create an empty string and use for loop to iterate the given dictionary for every iteration add key: value pair formate to empty string using concatenating(+) operator.

This version of the code uses an empty string converted to accumulate the formatted key-value pairs of the dictionary. After the loop, the trailing comma and space are removed from the accumulated string using rstrip(‘,’). The converted string and its type are then printed.

# Initializing dictionary
my_dict = {‘course’:’python’, ‘tutor’:’Richerd’, ‘duration’:’45 days’}
print(“Original dictionary:”,my_dict)
print (“Type of given dictionary:”, type(my_dict))

# Using an empty string and for loop
# to convert dictionaruy to string
# Create an empty string
converted = str()
for key in my_dict:
converted += key + “: ” + my_dict[key] + “, “
converted = converted.rstrip(‘, ‘)
print(“After converting the dictionary to a string:”,converted)
print(“Type of the converted string:”, type(str))

# Output:
# Original dictionary: {‘course’: ‘python’, ‘tutor’: ‘Richerd’, ‘duration’: ’45 days’}
# <class ‘dict’>
# After converting the dictionary to a string: course: python, tutor: Richerd, duration: 45 days,
# Type of the converted string: <class ‘type’>

6. Using For Loop and items() Function

From the above code, we have used an empty string and a for loop over the dictionary and converted it into a string manually. In this program, the for loop iterates through the dictionary using the items() method, which provides both keys and values. The f-string formatting is used to concatenate the key and value pairs into the converted string. The trailing comma and space are removed at the end, and then the converted string and its type are printed

# Initializing dictionary
my_dict = {‘course’:’python’, ‘tutor’:’Richerd’, ‘duration’:’45 days’}
print(“Original dictionary:”,my_dict)
print (“Type of given dictionary:”, type(my_dict))

# Convert the dictionary to a string
# Using for loop and items() function
# Create an empty string
converted = “”
for key, value in my_dict.items():
converted += f”{key}: {value}, “

# Removing the trailing comma and space
converted = converted.rstrip(‘, ‘)
print(“After converting the dictionary to a string:”, converted)
print(“Type of the converted string:”, type(converted))

Yields the same output as above.

Conclusion

In this article, I have explained how to convert a dictionary to a string in Python by using json.dumps(), str(), print(), empty string & for loop, and for loop & items() functions with examples.

Happy Learning !!

 How to convert a dictionary to a string in Python? You can convert a dictionary to a string using various methods of Python. One common approach is to use the json module to serialize the dictionary into a JSON-formatted string. The process of converting dictionaries to strings involves serialization, which means transforming data into a  Read More Python, Python Tutorial, Pending review by admin, Python Dictionary Examples, Python String Examples 

Leave a Reply

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