python

Get all keys from a dictionary in Python

Have you ever wondered how to get all the keys from a dictionary in Python? There are various methods for doing so, and I'll cover three of my favorites. The good thing about Python is its elegant simplicity, check out the following code:

subject = {
  "math": "m1",
  "physics": "p1",
  "chemistry": "c1",
  "dbms": "d1",
  "programming": "p1"
}

all_keys = list(subject.keys())

print(all_keys)

Output

['math', 'physics', 'chemistry', 'dbms', 'programming']

We know that a Python dictionary stores data in key-value pairs. And we can access the values of the dictionary using the key name. Sometimes, we need to get all the keys to the dictionary as a list and we can access them using their index.

In this post, we will explain methods and techniques that can be used to get the keys of a dictionary as a List.

Get all keys from a dictionary using Dicitonary.keys() function

This is the simplest method to get all the keys from a dictionary. This is a dictionary method that extracts all the keys from the dictionary and then you can get the list using the list() function by passing the Dictionary.keys() to it as a parameter.

user = {
  "first_name": "Tony",
  "last_name": "Stark",
  "username": "tony001",
  "email": "[email protected]"
}

result = list(user.keys())

print(result)

Output

['first_name', 'last_name', 'username', 'email']

Get all keys using Python For Loop

We can iterate over a dictionary using Python For Loop. In each iteration, we can append the key name to the list that we declare as a result.

# create a dictionary
my_dict = {
  "a": "1",
  "b": "2",
  "c": "3",
  "d": "4",
  "e": "5"
}

# declare a result varibale
result = []

# use for loop to get the keys
for key in my_dict:
  result.append(key)

# print the result
print(result)

Output

['a', 'b', 'c', 'd', 'e']
# create a dicitonary
numbers = {
  1: 10,
  2: 20,
  3: 30,
  4: 40,
}

# get all the dictionaries using Dictionary.keys() function
result = list(numbers.keys())

# print the result
print(result)

# Output -> [1, 2, 3, 4]
Here, we have defined a dictionary numbers and using list(numbers.keys()), we are getting all the keys from the dictionary.
Was this helpful?