Appearance
How to return dictionary keys as a list in Python?
In Python, you can use the dict.keys() method to return a view object that contains the keys of a dictionary. This view object can be converted to a list using the list() function.
Here's an example:
Return dictionary keys as a list in Python
python
# Create a sample dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Get a view of the dictionary keys
keys = my_dict.keys()
# Convert the view to a list
keys_list = list(keys)
print(keys_list)
# Output: ['a', 'b', 'c']
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
In Python 3.7 and later, you can also use the dict object directly in a list comprehension to get the list of keys, which is more concise and readable:
Return dictionary keys as a list in Python using the dict object directly
python
# Create a sample dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Using list comprehension
keys_list = [key for key in my_dict]
print(keys_list)
# Output: ['a', 'b', 'c']Note that since Python 3.7, standard dictionaries preserve insertion order. This means both methods above will return the keys in the exact order they were added to the dictionary. (For legacy Python versions prior to 3.7, dictionary order was not guaranteed, and collections.OrderedDict was used to maintain insertion order.)