Here are 3 approaches to extract dictionary values as a list in Python:
(1) Using a list() function:
my_list = list(my_dict.values())
(2) Using a List Comprehension:
my_list = [i for i in my_dict.values()]
(3) Using For Loop:
my_list = [] for i in my_dict.values(): my_list.append(i)
Next, you’ll see few examples of extracting dictionary values as a list.
Examples of Extracting Dictionary Values as a List in Python
Example 1: Use a list() function to extract dictionary values as a list
To start with a simple example, let’s create the dictionary below:
my_dict = {'A': 300, 'B': 150, 'C': 500, 'D': 850, 'E': 400} print(my_dict) print(type(my_dict))
You’ll then get the following dictionary:
{'A': 300, 'B': 150, 'C': 500, 'D': 850, 'E': 400}
<class 'dict'>
Note that the syntax of print(type(my_dict)) was added at the bottom of the syntax to demonstrate that we got a dictionary.
Now, let’s use a list() function to extract the dictionary values as a list:
my_dict = {'A': 300, 'B': 150, 'C': 500, 'D': 850, 'E': 400} my_list = list(my_dict.values()) print(my_list) print(type(my_list))
As you can see, the dictionary values were extracted as a list:
[300, 150, 500, 850, 400]
<class 'list'>
Example 2: Use a list comprehension to extract dictionary values
Now, let’s extract the dictionary values as a list using a list comprehension:
my_dict = {'A': 300, 'B': 150, 'C': 500, 'D': 850, 'E': 400} my_list = [i for i in my_dict.values()] print(my_list) print(type(my_list))
You’ll get the same list as in the previous example:
[300, 150, 500, 850, 400]
<class 'list'>
Example 3: Use a for loop to extract dictionary values
Finally, you may use a For Loop to extract the values as a list:
my_dict = {'A': 300, 'B': 150, 'C': 500, 'D': 850, 'E': 400} my_list = [] for i in my_dict.values(): my_list.append(i) print(my_list) print(type(my_list))
As before, you’ll get the same list:
[300, 150, 500, 850, 400]
<class 'list'>
Extract the Dictionary Values as a List of Lists
What if you’d like to extract the dictionary values as a list of lists?
For example, suppose that you have the following dictionary:
my_dict = {'A': [300, 305, 310], 'B': [150, 155, 160], 'C': [500, 505, 510]} print(my_dict) print(type(my_dict))
Result:
{'A': [300, 305, 310], 'B': [150, 155, 160], 'C': [500, 505, 510]}
<class 'dict'>
You can then apply the following syntax to extract the dictionary values as a list of lists:
my_dict = {'A': [300, 305, 310], 'B': [150, 155, 160], 'C': [500, 505, 510]} my_list = list(my_dict.values()) print(my_list) print(type(my_list))
You’ll now get a list of lists:
[[300, 305, 310], [150, 155, 160], [500, 505, 510]]
<class 'list'>
You may also want to check the following guide that explains how to extract dictionary keys as a list.