Here are 4 ways to extract dictionary keys as a list in Python:
(1) Using a list() function:
my_list = list(my_dict)
(2) Using dict.keys():
my_list = list(my_dict.keys())
(3) Using List Comprehension:
my_list = [i for i in my_dict]
(4) Using For Loop:
my_list = [] for i in my_dict: my_list.append(i)
Examples of extracting dictionary keys as a list
Example 1: Using a list() function
Let’s create a simple dictionary:
my_dict = {'Microwave': 300, 'Oven': 750, 'Dishwasher': 600, 'Refrigerator': 1200, 'Toaster': 150} print(my_dict) print(type(my_dict))
Result:
{'Microwave': 300, 'Oven': 750, 'Dishwasher': 600, 'Refrigerator': 1200, 'Toaster': 150}
<class 'dict'>
Note that print(type(my_dict)) was added at the bottom of the code to demonstrate that we got a dictionary.
Now let’s extract the dictionary keys as a list using my_list = list(my_dict):
my_dict = {'Microwave': 300, 'Oven': 750, 'Dishwasher': 600, 'Refrigerator': 1200, 'Toaster': 150} my_list = list(my_dict) print(my_list) print(type(my_list))
Result:
['Microwave', 'Oven', 'Dishwasher', 'Refrigerator', 'Toaster']
<class 'list'>
Example 2: Using dict.keys():
Alternatively, you may use my_list = list(my_dict.keys()) as follows:
my_dict = {'Microwave': 300, 'Oven': 750, 'Dishwasher': 600, 'Refrigerator': 1200, 'Toaster': 150} my_list = list(my_dict.keys()) print(my_list) print(type(my_list))
Result:
['Microwave', 'Oven', 'Dishwasher', 'Refrigerator', 'Toaster']
<class 'list'>
Example 3: Using List Comprehension
Using a List Comprehension:
my_dict = {'Microwave': 300, 'Oven': 750, 'Dishwasher': 600, 'Refrigerator': 1200, 'Toaster': 150} my_list = [i for i in my_dict] print(my_list) print(type(my_list))
Result:
['Microwave', 'Oven', 'Dishwasher', 'Refrigerator', 'Toaster']
<class 'list'>
Example 4: Using For Loop
Using a For Loop:
my_dict = {'Microwave': 300, 'Oven': 750, 'Dishwasher': 600, 'Refrigerator': 1200, 'Toaster': 150} my_list = [] for i in my_dict: my_list.append(i) print(my_list) print(type(my_list))
Result:
['Microwave', 'Oven', 'Dishwasher', 'Refrigerator', 'Toaster']
<class 'list'>