Python Dictionary – Get Keys as List

Dictionary is a collection of key:value pairs. You can get all the keys in the dictionary as a Python List.

dict.keys() returns an iterable of type dict_keys(). You can convert this into a list using list().

Also, you can use * operator, which unpacks an iterable. Unpack dict or dict.keys() in [] using * operator. It creates a list with dictionary keys in it.

Example 1 – Get Keys of Dictionary as Python List

In this example, we will create a Dictionary with some initial values and then get all the keys as a List into a variable.

example.py – Python Program

#initialize dictionary
aDict = {
    'tallest building':'Burj Khalifa',
    'longest river':'The Nile',
    'biggest ocean':'The Pacific Ocean'
}

# get keys as list
keys = list(aDict.keys())

#print keys
print(keys)
Try Online

Output

['tallest building', 'longest river', 'biggest ocean']

We got all the keys of dictionary as a list.

Example 2 – Get Keys of Dictionary as Python List using For Loop

In this example, we will create a list and add all the keys of dictionary one by one while iterating through the dictionary keys.

example.py – Python Program

#initialize dictionary
aDict = {
    'tallest building':'Burj Khalifa',
    'longest river':'The Nile',
    'biggest ocean':'The Pacific Ocean'
}

# get keys as list
keys = []
for key in aDict.keys():
	keys.append(key)

#print keys
print(keys)
Try Online

Output

['tallest building', 'longest river', 'biggest ocean']

Example 3 – Get Keys of Dictionary as Python List using * Operator

* operator unpacks a sequence. So, we will unpack the dictionary keys in [], which will create a list.

example.py – Python Program

#initialize dictionary
aDict = {
    'tallest building':'Burj Khalifa',
    'longest river':'The Nile',
    'biggest ocean':'The Pacific Ocean'
}

# get keys as list
keys = [*aDict.keys()]

#print the list
print(keys)
Try Online

Output

['tallest building', 'longest river', 'biggest ocean']

You can also use the dictionary directly instead of dict.keys() as shown below.

example.py – Python Program

#initialize dictionary
aDict = {
    'tallest building':'Burj Khalifa',
    'longest river':'The Nile',
    'biggest ocean':'The Pacific Ocean'
}

# get keys as list
keys = [*aDict]

#print the list
print(keys)
Try Online

Output

['tallest building', 'longest river', 'biggest ocean']

Conclusion

In this Python Tutorial, we learned how to get the keys of a dictionary as Python List.