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:
# 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']
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:
# 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']
It is worth mentioning that the order of items in dictionary is not guaranteed so the order of keys in list also may change when you will use the above approach. Python 3.7 and later versions guarantee that the keys will be returned in insertion order, but before that there is no such guarantee, and in that case, you need to use collections.OrderedDict
to make sure the keys will be returned in the same order.