0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert Dictionary Keys to List

You can convert dictionary keys to a list in Python by using list(your_dict.keys()), which returns a list of all keys.
📋

Examples

Input{'a': 1, 'b': 2, 'c': 3}
Output['a', 'b', 'c']
Input{1: 'apple', 2: 'banana'}
Output[1, 2]
Input{}
Output[]
🧠

How to Think About It

To convert dictionary keys to a list, think of the dictionary as a collection of pairs. You want to take only the first part of each pair, which are the keys, and gather them into a new list. Python provides a simple way to get all keys, then you just turn that collection into a list.
📐

Algorithm

1
Get the dictionary input.
2
Extract all keys from the dictionary.
3
Convert the keys collection into a list.
4
Return or print the list of keys.
💻

Code

python
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = list(my_dict.keys())
print(keys_list)
Output
['a', 'b', 'c']
🔍

Dry Run

Let's trace {'a': 1, 'b': 2, 'c': 3} through the code

1

Start with dictionary

my_dict = {'a': 1, 'b': 2, 'c': 3}

2

Extract keys

my_dict.keys() returns dict_keys(['a', 'b', 'c'])

3

Convert to list

list(dict_keys(['a', 'b', 'c'])) becomes ['a', 'b', 'c']

StepOperationResult
1Dictionary{'a': 1, 'b': 2, 'c': 3}
2Get keysdict_keys(['a', 'b', 'c'])
3Convert to list['a', 'b', 'c']
💡

Why This Works

Step 1: Dictionary keys method

The keys() method returns a view of all keys in the dictionary.

Step 2: Convert keys view to list

Using list() on the keys view creates a new list containing all keys.

🔄

Alternative Approaches

Using list comprehension
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = [key for key in my_dict]
print(keys_list)
This manually collects keys into a list; slightly longer but clear.
Using unpacking operator
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_list = [*my_dict]
print(keys_list)
Unpacks keys directly into a list; concise and modern syntax.

Complexity: O(n) time, O(n) space

Time Complexity

Extracting keys and converting to a list requires visiting each key once, so it takes linear time relative to the number of keys.

Space Complexity

A new list is created to hold all keys, so space grows linearly with the number of keys.

Which Approach is Fastest?

Using list(dict.keys()) or unpacking [*dict] are both efficient and clear; list comprehension is slightly more verbose but similar in speed.

ApproachTimeSpaceBest For
list(dict.keys())O(n)O(n)Clarity and standard usage
List comprehensionO(n)O(n)Explicit iteration, good for adding conditions
Unpacking operator [*dict]O(n)O(n)Concise and modern syntax
💡
Use list(your_dict.keys()) for a quick and clear way to get keys as a list.
⚠️
Trying to convert the dictionary itself to a list returns keys but as a list of keys, not values or items.