Get the First Key in Python Dictionary

  1. Get the First Key in Dictionary Using iter() Function
  2. Get the First Key in Dictionary Using list() Function
  3. Get the First Key in Dictionary Using the for Loop

This tutorial explains how we can get the first key in Python dictionary. By the first key, we mean the key saved in the first index of the dictionary.

In Python versions 3.7 and above, where a dictionary is ordered, we can get the first key, by first converting the dictionary into an iterated object using iter() function and then fetching its first index key using the next function.

The second method is to convert the dictionary into a list using the list() function and then get the key at the 0th index.

The third method is to get the first key in a dictionary using the for loop.

Get the First Key in Dictionary Using iter() Function

The code example given below shows how we can get the first key in the Python dictionary using the iter() and next() functions.

my_dict = { 'London': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

print(next(iter(my_dict)))

Output:

London

Get the First Key in Dictionary Using list() Function

We can also first convert the dict type into list using the list() function and then get the first key at 0th index.

my_dict = { 'London': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

print(list(my_dict.keys())[0])

Output:

London

Get the First Key in Dictionary Using the for Loop

Another method is to get the first key in a dictionary using the for loop and break the loop after we get the first key of the dictionary.

Code example:

my_dict = { 'London': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

for key, value in my_dict.items():
  print(key)
  break

Output:

London
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Dictionary

  • Save a Dictionary to a File in Python
  • Merge Two Dictionaries in Python 2 and 3