Skip to content
Home / Fundamentals

Returning Dictionary Keys as a List in Python

In Python, a dictionary is a collection of key-value pairs. You can access the keys of a dictionary using the keys() method, which returns a view object that displays a list of all the keys in the dictionary.

However, if you want to return the keys as a list, you can use the list() function to convert the view object to a list.

Here's an example of how to do this:

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

# Get the keys of the dictionary
keys = my_dict.keys()

# Convert the keys to a list
keys_list = list(keys)

# Print the list of keys
print(keys_list)
['a', 'b', 'c']
You can also use a dictionary comprehension to return the keys of a dictionary as a list. Here's an example:

```python
# Define a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Use a dictionary comprehension to get the keys of the dictionary
keys_list = [key for key in my_dict]

# Print the list of keys
print(keys_list)
['a', 'b', 'c']

If you want to return only the keys that meet certain criteria, you can use a dictionary comprehension with a conditional statement. For example, to return only the keys that have a value greater than 2, you can do the following:

# Define a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Use a dictionary comprehension with a conditional statement to get the keys with values greater than 2
keys_list = [key for key, value in my_dict.items() if value > 2]

# Print the list of keys
print(keys_list)
['c', 'd']

You can also use the filter() function to return the keys that meet certain criteria. For example, to return only the keys that have a value less than 3, you can do the following:

# Define a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Use the filter() function to get the keys with values less than 3
keys_list = list(filter(lambda x: my_dict[x] < 3, my_dict))

# Print the list of keys
print(keys_list)
['a', 'b']

You can also use the get() method to return the keys of a dictionary as a list. The get() method returns the value of a key in the dictionary, or a default value if the key is not found. To return the keys of the dictionary as a list, you can pass the keys as the first argument to the get() method and set the default value to None.