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

Examples

1. Convert dictionary keys to a 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)

Output

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

2. Convert dictionary keys to a 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)

Output

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

3. Convert dictionary keys to a 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)

Output

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

Summary

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