In this Python tutorial, you will learn how to get the keys of a dictionary as a list, using keys() method of dict class, or using sequence unpacking operator.

Python – Get Keys in Dictionary as a 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, we can use * operator, which unpacks an iterable. Unpack dict or dict.keys() in [] using * operator. It creates a list with dictionary keys in it.

Examples

1. Get keys of a dictionary as a 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.

Python Program

</>
Copy
#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)

Output

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

We got all the keys of dictionary as a list.

Reference tutorials for the above program

2. Get keys of a dictionary as a 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.

Python Program

</>
Copy
#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)

Output

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

Reference tutorials for the above program

3. Get keys of a dictionary as a list using * Operator

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

Python Program

</>
Copy
#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)

Output

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

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

Python Program

</>
Copy
#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)

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.