Convert Python Dictionary Keys to List

Python Dictionary Keys to List

To convert Python Dictionary keys to List, you can use dict.keys() method which returns a dict_keys object. This object can be iterated, and if you pass it to list() constructor, it returns a list object with dictionary keys as elements.

A simple code snippet to convert dictionary keys to list is

keysList = list(myDict.keys())

Example 1: Dictionary Keys to List using dict.keys()

In the following program, we have a dictionary initialized with three key:value pairs. We will use dict.keys() method to get the dict_keys object. We pass dict.keys() as argument to list() constructor. list() returns the list of keys.

Python Program

myDict = {'a': 'apple', 'b': 'banana', 'c': 'cherry'}
keysList = list(myDict.keys())
print(keysList)
Run

Output

['a', 'b', 'c']

Example 2: Dictionary Keys to List using List Comprehension

We can also use List Comprehension to get the keys of dictionary as elements of a list.

Python Program

myDict = {'a': 'apple', 'b': 'banana', 'c': 'cherry'}
keysList = [key for key in myDict]
print(keysList)
Run

Output

['a', 'b', 'c']

Example 3: Dictionary Keys to List using For Loop

If you are not comfortable with List comprehension, let us use For Loop. When you iterate on the dictionary, you get next key during each iteration. Define an empty list keysList to store the keys and append the key during each iteration in for loop.

Python Program

myDict = {'a': 'apple', 'b': 'banana', 'c': 'cherry'}

keysList = []
for key in myDict:
    keysList.append(key)

print(keysList)
Run

Output

['a', 'b', 'c']

Summary

In this tutorial of Python Examples, we learned how to get Dictionary keys as List.