![]() |
Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various concepts and methods. Here, we will see how we can convert a dictionary into a list of values in Python. Convert Dictionary to List of Values in PythonBelow are some of the ways by which we can convert a dictionary to a list of values in Python:
Convert Dictionary to List Using For LoopThe below method converts dictionary data into a list list_of_data using a for loop. It iterates through the keys of the dictionary, retrieves the corresponding values using data.get(key), and appends a list containing the key-value pair to the list_of_data list. Python
Output
<type 'list'> [[1, 'Gaurav'], [2, 'Sanket'], [3, 'Anjali'], [4, 'Priyanka']] Python Convert Dictionary to List Using .items() FunctionThe below method uses the items() method to convert a dictionary (data) into a list (list_of_data), containing key-value pairs. The resulting list is then printed, demonstrating the transformation of dictionary data into a list of values. Python
Output
<type 'list'> [(1, 'Gaurav'), (2, 'Sanket'), (3, 'Anjali'), (4, 'Priyanka')] Python Dictionary to List Using Zip FunctionUsing the zip function, the provided code converts a dictionary (data) into a list (list_of_data) by combining keys and values into tuples and then converting them into a list. This method showcases the demonstration of the zip function for creating a list of values from a dictionary. Python
Output
<type 'list'> [(1, 'Gaurav'), (2, 'Sanket'), (3, 'Anjali'), (4, 'Priyanka')] ConclusionIn conclusion, various methods have been explored for converting a dictionary to a list of values in Python. Whether using for loops, the .items() function, list comprehension, the zip function, or the map function, each approach offers a way to achieve the conversion. Developers can choose the method that best fits their preferences and coding style, enhancing flexibility in managing and manipulating data structures. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |