Convert Dictionary to String List in Python
Last Updated :
31 Jan, 2024
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:
- Using str() Function
- Using json.dumps() Function
- Using a For Loop
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.
Python3
dic = { 1 : 'Mercedes' , 2 : 'Audi' , 3 : 'Porsche' , 4 : 'Lambo' }
print ( type (dic))
print (f "Dictionary: {dic}" )
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.
Python3
import json
di = { 1 : 'Nike' , 2 : 'Gucci' , 3 : 'Balenciaga' , 4 : 'Fossil' , 5 : 'Lacoste' }
print ( type (di))
print (f "Dictionary: {di}" )
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.
Python3
my_dict = { 'name' : 'Bob' , 'age' : 28 , 'city' : 'Paris' }
string_list = []
for key, value in my_dict.items():
string_list.append(f '{key}: {value}' )
print (string_list)
|
Output
['name: Bob', 'age: 28', 'city: Paris']
Share your thoughts in the comments
Please Login to comment...