Get the First Key in Python Dictionary
-
Get the First Key in Dictionary Using
iter()
Function -
Get the First Key in Dictionary Using
list()
Function -
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