How to convert a dictionary to a string in Python?

Convert A Dictionary To A String In Python

Dive into the exciting world of Python by exploring various techniques to transform dictionaries into strings. This comprehensive guide unveils the different methods and scenarios where each can be most effective, enabling you to harness Python’s powerful features.

Python offers various methods to convert a dictionary into a string. These include using the str() function, the json.dumps() function, and several loop constructs. The conversion can be tailored to include both keys and values, or either of them separately.


What is a dictionary in Python?

A dictionary is a Python object which is used to store the data in the key:value format. The key and its corresponding value are separated by a colon (:). And each key:value pair in the dictionary is separated by a comma (,). A dictionary in Python is always enclosed in the curly brackets {}.

A Python dictionary is an unordered data structure unlike a list or a tuple in Python. We can directly access any value of a Python dictionary just by using its corresponding key. Let’s see how we can create a dictionary through Python code.

# Create a Python dictionary
dc = {'py': "PYTHON", 'cpp': "C++", 'mat': "MATLAB"}
print(type(dc))
print(dc)

Output:

<class 'dict'> 
{'py': 'PYTHON', 'cpp': 'C++', 'mat': 'MATLAB'}

What is a string in Python?

A string is also a Python object which is the most commonly used data structure and it is used to store a sequence of characters. Anything enclosed inside the single, double, or triple quotes is a string in Python. In Python, the single and the double quotes can be used interchangeably to represent a single line string while triple quotes are used to store multi-line strings. Let’s create one string through Python code.

# Create a Python dictionary
sr = "py: PYTHON cpp: C++ mat: MATLAB"
print(type(sr))
print(sr)

Output:

<class 'str'> 
py: PYTHON cpp: C++ mat: MATLAB

Different ways to convert a dictionary to a string in Python

In Python, there are multiple ways to convert a dictionary to a string. Let’s discuss some of the most commonly used methods/ways to do it.

1. Using the str() function

In this method of converting a dictionary to a string, we will simply pass the dictionary object to the str() function.

# Create a Python dictionary
dc = {'A': 'Android', 'B': 'Bootstrap', 'C': 'C Programming', 'D': 'Dart'}
print(type(dc))
print(f"Given dictionary: {dc}")

# Convert the dictionary to a string
# using str() function
sr = str(dc)
print(type(sr))
print(f"Converted string: {sr}")

Output:

<class 'dict'> 
Given dictionary: {'A': 'Android', 'B': 'Bootstrap', 'C': 'C Programming', 'D': 'Dart'} 
<class 'str'> 
Converted string: {'A': 'Android', 'B': 'Bootstrap', 'C': 'C Programming', 'D': 'Dart'}

2. Using json.dumps() function

In this method of converting a dictionary to a string, we will pass the dictionary object to the json.dumps() function. To use the json.dumps() function we have to import the JSON module which is a built-in package in Python.

# Import Python json module
import json

# Create a Python dictionary
dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
print(type(dict))
print(f"Given dictionary: {dict}")

# Convert the dictionary to a string
# using json.dumps() function
str = json.dumps(dict)
print(type(str))
print(f"Converted string: {str}")

Output:

<class 'dict'> 
Given dictionary: {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5} 
<class 'str'> 
Converted string: {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}

3. Using an empty string and for loop

In this method of converting a dictionary to a string, we will simply access the keys of the dictionary by iterating through the dictionary object using a for loop. Then we access the value corresponding to each key and add the key: value pair to an empty string.

# Create a Python dictionary
dict = {'D': "Debian", 'U': "Ubuntu", 'C': "CentOS"}
print(type(dict))
print(f"Given dictionary- {dict}")

# Create an empty string
str = ""

# Convert the dictionary to a string
# using for loop only
for item in dict:
    str += item + ':' + dict[item] + ' '
print(type(str))
print(f"Converted string- {str}")

Output:

<class 'dict'> 
Given dictionary- {'D': 'Debian', 'U': 'Ubuntu', 'C': 'CentOS'} 
<class 'str'> 
Converted string- D:Debian U:Ubuntu C:CentOS

4. Using an empty string, a for loop, and items() function

In this method of converting a dictionary to a string, we will first access the key:value pair by iterating through the dictionary object using a for loop and items() function. Then we add each key:value pair to an empty string.

# Create a Python dictionary
dict = {'Google': "GCP", 'Microsoft': "Azure", 'Amazon': "AWS"}
print(type(dict))
print(f"Given dictionary- {dict}")

# Create an empty string
str = ""

# Convert the dictionary to a string
# using for loop and items() function
for key, value in dict.items():
    str += key + ':' + value + ' '
print(type(str))
print(f"Converted string- {str}")

Output:

<class 'dict'> 
Given dictionary- {'Google': 'GCP', 'Microsoft': 'Azure', 'Amazon': 'AWS'} 
<class 'str'> 
Converted string- Google:GCP Microsoft:Azure Amazon:AWS  

5. Using a for loop, items(), and str.join() function

In this method of converting a dictionary to a string, we will iterate through the dictionary object using a for loop and add the key & its value. Then we will use the str.join() function to join all the key: value pairs together as one single string.

# Create a Python dictionary
dict = {'Google': " Chrome", 'Microsoft': " Edge", 'Apple': " Safari"}
print(type(dict))
print(f"Given dictionary: {dict}")

# Convert the dictionary to a string
# using str.join() and items() function
str = ', '.join(key + value for key, value in dict.items())
print(type(str))
print(f"Converted string: {str}")

Output:

<class 'dict'> 
Given dictionary: {'Google': '-Chrome', 'Microsoft': '-Edge', 'Apple': '-Safari'} 
<class 'str'> 
Converted string: Google-Chrome, Microsoft-Edge, Apple-Safari

In Python, we can also convert the keys and values of a dictionary object into two separate strings rather than converting the key: value pairs into a single string. Let’s discuss it one by one.

Convert the keys of a dictionary to a string

First, we will discuss the different ways to convert the keys of the dictionary object to a string.

1. Using an empty string and for loop

# Create a Python dictionary
dict = {'OS': "Operating System", 'DBMS': "Database Management System", 'CN': "Computer Network"}
print(type(dict))
print(f"Given dictionary- {dict}")

# Create an empty string
str = ""

# Convert the dictionary keys into a string
# using for loop only
for item in dict:
    str += item + " "
print(type(str))
print(f"Keys in string- {str}")

Output:

<class 'dict'> 
Given dictionary- {'OS': 'Operating System', 'DBMS': 'Database Management System', 'CN': 'Computer Network'} 
<class 'str'> 
Keys in string- OS DBMS CN

2. Using a for loop and str.join() function

# Create a Python dictionary
dict = {'gcc': "C program", 'g++': "C++ program", 'py': "Python Program"}
print(type(dict))
print(f"Given dictionary: {dict}")

# Convert the dictionary keys into a string
# using str.join()
str = ', '.join(key for key in dict)
print(type(str))
print(f"Keys in string: {str}")

Output:

<class 'dict'> 
Given dictionary: {'gcc': 'C program', 'g++': 'C++ program', 'py': 'Python Program'} 
<class 'str'> 
Keys in string: gcc, g++, py

Convert the values of a dictionary to a string

Now let’s discuss the different ways to convert the values of the dictionary object to a string.

1. Using an empty string and for loop

# Create a Python dictionary
dict = {'OS': "Operating_System", 'DBMS': "Database_Management_System", 'CN': "Computer_Network"}
print(type(dict))
print(f"Given dictionary- {dict}")

# Create an empty string
str = ""

# Convert the dictionary values into a string
# using for loop only
for item in dict:
    str += dict[item] + " "
print(type(str))
print(f"Values in string- {str}")

Output:

<class 'dict'> 
Given dictionary- {'OS': 'Operating_System', 'DBMS': 'Database_Management_System', 'CN': 'Computer_Network'} 
<class 'str'> 
Values in string- Operating_System Database_Management_System Computer_Network 

2. Using a for loop and str.join() function

# Create a Python dictionary
dict = {'gcc': "C program", 'g++': "C++ program", 'py': "Python Program"}
print(type(dict))
print(f"Given dictionary: {dict}")

# Convert the dictionary values into a string
# using str.join()
str = ', '.join(dict[item] for item in dict)
print(type(str))
print(f"Values in string: {str}")

Output:

<class 'dict'> 
Given dictionary: {'gcc': 'C program', 'g++': 'C++ program', 'py': 'Python Program'} 
<class 'str'> 
Values in string: C program, C++ program, Python Program

Conclusion

After exploring the myriad ways to convert Python dictionaries into strings, you should now be proficient in applying these techniques, even for key-value separation. Ready to apply these concepts in your next Python project?