Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
dictionary
keys
list

How to get dictionary keys as a list in Python

Gutha Vamsi Krishna

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:

  1. Using dict.keys().
  2. 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 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)

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 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

python
communitycreator
dictionary
keys
list
RELATED COURSES

View all Courses

Keep Exploring