How to get dictionary keys as a list in Python
In this shot, we will learn to get dictionary keys as a list using Python.
In Python, a dictionary is an unordered collection of key-value pairs where the keys are unique.
We can get the dictionary keys as a list in two ways:
- Using
dict.keys(). - Unpacking into list literal.
Using dict.keys()
The approach is to:
- Get the iterable of keys with the
dict.keys()method. - Cast the iterable to list.
#declare and initialize the dictionaryfruits = {"orange":20,"apple":24,"guava":43,"watermelon":10,}#get keys iterablefruits_iterable = fruits.keys()#cast iterable to listlist_of_keys = list(fruits_iterable)#print the list of keys of a dictionaryprint(list_of_keys)
Unpack into list literal
We can get the list of keys from a dictionary by unpacking all the keys into a list using *.
In the following example, we will unpack using [*fruits], where fruits is the dictionary. * will unpack all the keys from the dictionary fruits.
#declare and initialize the dictionaryfruits = {"orange":20,"apple":24,"guava":43,"watermelon":10,}#unpack into list literallist_of_keys = [*fruits]#print the list of keys of a dictionaryprint(list_of_keys)