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 a For Loop:
my_list = []
for i in my_dict.values():
my_list.append(i)
Examples
Example 1: Use a list() function to extract dictionary values as a list
To start with a simple example, create a dictionary as follows:
my_dict = {"A": 300, "B": 150, "C": 500, "D": 850, "E": 400}
print(my_dict)
print(type(my_dict))
You’ll then get this dictionary:
{'A': 300, 'B': 150, 'C': 500, 'D': 850, 'E': 400}
<class 'dict'>
Note that “print(type(my_dict))” was added at the bottom of the script to demonstrate that you got a dictionary.
Next, 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, 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, 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 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))
The resulted dictionary:
{'A': [300, 305, 310], 'B': [150, 155, 160], 'C': [500, 505, 510]}
<class 'dict'>
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'>
if needed, check the following guide that explains how to extract dictionary keys as a list.