Python Convert Dictionary to List of Values
Last Updated :
07 Feb, 2024
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 Python
Below are some of the ways by which we can convert a dictionary to a list of values in Python:
- Using for loop
- Using items() Function
- Using Zip Function
Convert Dictionary to List Using For Loop
The 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
data = { 1 : "Gaurav" , 2 : "Sanket" , 3 : "Anjali" , 4 : "Priyanka" }
list_of_data = []
for key in data:
list_of_data.append([key, data.get(key)])
print ( type (list_of_data))
print (list_of_data)
|
Output
<type 'list'>
[[1, 'Gaurav'], [2, 'Sanket'], [3, 'Anjali'], [4, 'Priyanka']]
Python Convert Dictionary to List Using .items() Function
The 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
data = { 1 : "Gaurav" , 2 : "Sanket" , 3 : "Anjali" , 4 : "Priyanka" }
list_of_data = list (data.items())
print ( type (list_of_data))
print (list_of_data)
|
Output
<type 'list'>
[(1, 'Gaurav'), (2, 'Sanket'), (3, 'Anjali'), (4, 'Priyanka')]
Python Dictionary to List Using Zip Function
Using 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
data = { 1 : "Gaurav" , 2 : "Sanket" , 3 : "Anjali" , 4 : "Priyanka" }
list_of_data = list ( zip (data.keys(), data.values()))
print ( type (list_of_data))
print (list_of_data)
|
Output
<type 'list'>
[(1, 'Gaurav'), (2, 'Sanket'), (3, 'Anjali'), (4, 'Priyanka')]
Conclusion
In 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.
Share your thoughts in the comments
Please Login to comment...