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:
dict.keys()
.dict.keys()
The approach is to:
dict.keys()
method.#declare and initialize the dictionary fruits = { "orange":20, "apple":24, "guava":43, "watermelon":10, } #get keys iterable fruits_iterable = fruits.keys() #cast iterable to list list_of_keys = list(fruits_iterable) #print the list of keys of a dictionary print(list_of_keys)
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 dictionary fruits = { "orange":20, "apple":24, "guava":43, "watermelon":10, } #unpack into list literal list_of_keys = [*fruits] #print the list of keys of a dictionary print(list_of_keys)
RELATED TAGS
CONTRIBUTOR
View all Courses