How To Find the First Key In The Dictionary In Python – With Examples

The insertion order is maintained in the dictionary since version Python 3.7.

You can find the first key in the dictionary in Python using the list(yourdict.keys())[0] method.

Basic Example

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

first_key = list(yourdict.keys())[0]

print(first_key)

Output

    one

This tutorial is only applicable only if you’re using Python version 3.7 or later.

If you try to get the first in the dictionary with python versions earlier than 3.7, you may get any random keys because of non-maintenance of the insertion order.

Different methods are available to find the first key in the dictionary in Python. Let us learn each method.

Checking Python Version Information

Python dictionaries are ordered since version 3.7.

You can check the python version using the below script.

Code

import sys

print(sys.version)

Output

3.8.2 (default, Sep  4 2020, 00:03:40) [MSC v.1916 32 bit (Intel)]

Using Keys() And List function

The keys() method returns a copy of the dictionary’s list of keys.

To find the first key of the dictionary,

  • Convert the dictionary keys into a list using the list() method.
  • Access the first item in the list using the index 0.

Use this method when you just want the first key of the dictionary.

Code

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

first_key = list(yourdict.keys())[0]

print(first_key)

Output

    one

Using Items() and For Loop

The items() method returns the key-value pair of the dictionary.

To find the first key of the dictionary using the items() method,

Use this method when you want the key and value of the first item in the dictionary.

Code

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

for k,v in yourdict.items():
    print(k)
    break

Output

    one

Using Iters() method

The iters() method returns an iterator object of the dictionary.

To get the first key of the dictionary,

  • Get the iterator object of the dictionary using the iters() method
  • Move the cursor in the iterator to the first item using the next() method. You’ll have the first key in the dictionary.

Use it only when you need an iterator object of the dictionary and need to move forward or backwards during the iteration.

Code

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

dict_iterator = iter(yourdict)

print(next(dict_iterator))

Output

    one

Get First N Keys In the Dictionary

To find the first N keys,

  • Get the list of keys using the keys() method
  • Use the list slicing to get the first n keys.

For example, to get the first two items, use :2.

Code

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

n = 2

first_n_keys = list(yourdict.keys())[:n]

print(first_n_keys)

Output

    ['one', 'two']

Additional Resources

Leave a Comment