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.
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
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>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
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.)