How to get the first key of a dictionary in Python?

A Python dictionary is an unordered collection of key-value pairs. When we are working with Python dictionaries, we may sometimes need the first key of the dictionary.

So, how to get the first key of a dictionary in Python?

To get the first key of a dictionary, we can take the help of the built-in list() function. If we pass the name of the dictionary as an argument to the list() function, it will return a list containing all keys of the dictionary. Later, we can get the first key from this list by accessing its first element.

Example:

student = {
    'name': 'John',
    'age': 22,
    'gender': 'Male'
}

all_keys = list(student)
print('All Keys: ', all_keys)

# Get the first key using all_keys[0]
print('First Key: ', all_keys[0])

Output:

All Keys:  ['name', 'age', 'gender']
First Key:  name

There are several other methods also which can help you to get the first key of the dictionary. But, this is the simplest method to achieve this task.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts