Python dictionary allows you to store information in key-value pairs. But sometimes you build an API for these data then you have to get access to the values. In this tutorial, you will know the various methods to convert dictionary values to list in python.
Method to convert dictionary values to list in Python
Let’s look at all the methods to convert dictionary values to lists in python.
Below is the sample dictionary that will be used in all the methods.
sample_dict = {'a': 10, 'b': 20, 'c': 30}
Method 1: Using the values() method
The easiest way to convert the values of a Python dictionary into a list is the use the values() function. This function will return a list of all the values that are in the dictionary. You have to pass the dictionary as a parameter to the values() function.
The values() method returns us an iterable view of the values. Lastly, you will turn it into a list by calling the list() function on it.
Run the below lines of code.
sample_dict = {'a': 10, 'b': 20, 'c': 30}
sample_list = list(sample_dict.values())
print(sample_list)
Output
[10,20,30]
Method 2: Using list comprehension
You can also use list comprehension to convert the values of a Python dictionary to a list. In this method, you have to just pass the dictionary as an argument to the list comprehension. It will output a list with the values of the dictionary. Here you will also use the values() function inside the list comprehension.
sample_dict = {'a': 10, 'b': 20, 'c': 30}
sample_list = [value for value in sample_dict.values()]
print(sample_list)
Output
[10, 20, 30]
Method 3: Convert dictionary values to list Using the itervalues() method
The itervalues() method works similarly to values(). It does not provide a view but it returns an iterator. It is very helpful when you are dealing with large dictionaries. At last, you call the list() function on the returned value to turn the keys into a list.
Execute the below lines of code to convert values to list.
sample_dict = {'a': 10, 'b': 20, 'c': 30}
sample_list = list(sample_dict.itervalues())
print(sample_list)
Output
[10, 20, 30]
Method 4: Using for loop
You can also create a list from a python dictionary using for loop. Firstly you will create an empty list and then iterate through the dictionary to add the values to it.
sample_dict = {'a': 10, 'b': 20, 'c': 30}
final_list =[]
for key, value in sample_dict.items():
final_list.append(value)
print(final_list)
Output
[10, 20, 30]
Method 5: Using the map() function
You can also use the map() function to convert the dictionary value to the list. You have to also use the lambda function as a function of the map function. It will result in an iterator of the values. Finally, you have to call the list() function to convert the values to the list.
sample_dict = {'a': 10, 'b': 20, 'c': 30}
sample_list = list(map(lambda x: x[1], sample_list.items()))
print(sample_list)
[10, 20, 30]
Leave a Reply