Get list of dictionary keys in Python

In Python, you can add dictionary keys to a list. This can be achieved with the keys function of a dictionary.

my_dict = {'firstname': 'John', 'lastname': 'Brown', 'age': 34}
my_list = []

for key in my_dict.keys():
    my_list.append(key)

print(my_list)

The keys function is used in the for loop to get the key part, instead of value. Each key is added at the end of the my_list list using the append function.

If you print the list, you are going to get the list of dictionary keys:

['firstname', 'lastname', 'age']