Open In App

Convert Dictionary to String List in Python

Dictionaries represent a data structure for the key-value pairs in Python. A lot of times, one needs to transform a dictionary into a string list to print logs or perform data manipulations. In this article, the dictionary data type is converted to a string list in Python using many concepts and methods.

Convert Dictionary to String List in Python

Below are some of the ways by which we can convert a dictionary to a string list in Python:



Convert Dictionary to String Using str() Function

In this str() function, we just need to send the dictionary as an object that will convert a dict into a string.




# dict to string in Python using str()
# Creating a dictionary
dic = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
print(type(dic))
print(f"Dictionary: {dic}")
 
# Converting the dict to a string by using str() func
stri = str(dic)
print(type(stri))
print(f"String: {stri}")

Output

<class 'dict'>
Dictionary: {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}
<class 'str'>
String: {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}

Python Convert Dictionary to String Using json.dumps() Function

With this method, we can bypass the dictionary to the json.dumps() function and convert a dictionary into string avoiding (skipping) that: Since the json.dumps () function is a built-in Python module, we need to import it before using it.




# Importing json module
import json
 
# Creating a dictionary
di = {1:'Nike', 2:'Gucci', 3:'Balenciaga', 4:'Fossil', 5: 'Lacoste'}
print(type(di))
print(f"Dictionary: {di}")
 
# Converting the dictionary into a string by using json.dumps() function
stri = json.dumps(di)
print(type(stri))
print(f"String: {stri}")

Output
<class 'dict'>
Dictionary: {1: 'Nike', 2: 'Gucci', 3: 'Balenciaga', 4: 'Fossil', 5: 'Lacoste'}
<class 'str'>
String: {"1": "Nike", "2": "Gucci", "3": "Balenciaga", "4": "Fossil", "5": "Lacoste"}

Python Dictionary to String List Using a For Loop

Using a traditional for loop, the formatted strings are appended to an accumulated list by iterating over the key-value pairs of the given dictionary.




# Example Dictionary
my_dict = {'name': 'Bob', 'age': 28, 'city': 'Paris'}
 
# Convert to String List
string_list = []
for key, value in my_dict.items():
    string_list.append(f'{key}: {value}')
 
# Output
print(string_list)

Output
['name: Bob', 'age: 28', 'city: Paris']


Article Tags :