Get the First Key in Python Dictionary

Get the First Key in Python Dictionary

Muhammad Waiz Khan Mar-08, 2021 Jan-25, 2021 Python 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

Related Article - Python Dictionary

  • Check if a Key Exists in a Dictionary in Python
  • Convert a Dictionary to a List in Python
  • Get All the Files of a Directory
  • Find Maximum Value in Python Dictionary
  • Delete a File and Directory in Python
  • Sort a Python Dictionary by Value