How to obtain the first key in a Python dictionary
Recall that dictionaries are essentially key-value pairs and are thus useful to store information that can be represented in such forms. Here is an example of a dictionary that stores months and the number of days in each.
The typical way to access dictionaries is via the (key,value) pair mappings. Internally, dictionaries are stored in an ordered fashion and you might find the need to obtain the first key in the dictionary. In our case the first key is “January” (and the first value is 31). There are three ways to do so.
Method 1: Obtain all keys in a list and select the first element
In the first approach, we use the keys() method to obtain all the keys of a dictionary and convert it into a list using the list() constructor. Now we can simply obtain the first key by selecting the first element of this list:
The output (for the above dictionary) is:
Note that you need the list() constructor step because without it, the keys() method returns an object that is not indexable. Thus, if you try:
you will obtain:
Method 2: Setup an iterator and find the first element using next()
The second method is the more Python-ic way as it uses dictionaries in the way they are intended to be used. We use the iter() function to setup an iterator that sweeps over the dictionary and use the next() function to obtain the next element. Because the very first “next” element is the first element, we obtain what we are looking for:
This results in:
Note that you can keep using next() as it simply moves the “pointer’ forward and returns the next element.
If we do:
we will obtain:
Method 3: Find the keys and use the unpacking operator to obtain the first key
This method is a variant of the first approach. We obtain the keys using the keys() method. Then, instead of converting the keys into a list, we unpack the keys using the unpacking operator, like so:
The output will be:
Thus, we have learnt three different ways to obtain the first key in a Python dictionary. Which one is your favorite?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.