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
# initial dictionary data = { 1 : "Gaurav" , 2 : "Sanket" , 3 : "Anjali" , 4 : "Priyanka" } # empty list to store key-value pairs list_of_data = [] # iterate through dictionary for key in data: # append key-value pair to the list list_of_data.append([key, data.get(key)]) # print the resulting list print ( type (list_of_data)) print (list_of_data) |
<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
# initial dictionary data = { 1 : "Gaurav" , 2 : "Sanket" , 3 : "Anjali" , 4 : "Priyanka" } # convert dict items into list list_of_data = list (data.items()) # printing the resulting list print ( type (list_of_data)) print (list_of_data) |
<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
# initial dictionary data = { 1 : "Gaurav" , 2 : "Sanket" , 3 : "Anjali" , 4 : "Priyanka" } # Zip tuple of kays & values into list list_of_data = list ( zip (data.keys(), data.values())) # printing the resulting list print ( type (list_of_data)) print (list_of_data) |
<type 'list'> [(1, 'Gaurav'), (2, 'Sanket'), (3, 'Anjali'), (4, 'Priyanka')]
Python Convert Dictionary to List of Values
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.