![]() |
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 PythonBelow are some of the ways by which we can convert a dictionary to a string list in Python:
Convert Dictionary to String Using str() FunctionIn this str() function, we just need to send the dictionary as an object that will convert a dict into a string. Python3
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() FunctionWith 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
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 LoopUsing 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
Output
['name: Bob', 'age: 28', 'city: Paris'] |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |