How to Get the next key in Dictionary in Python?


Dictionaries are powerful data types of Python. It consists of key-value pairs. Operations like searching, appending, etc., can be done efficiently through this data type. While accessing values in a dictionary is straightforward, there may be situations where you need to find the next key in a dictionary. Python provides several ways to achieve this, depending on your specific requirements. In this article, we will explore different methods to get the next key in a dictionary in Python.

Using The keys And index Method

The dictionaries are unordered collections in Python. Hence we first need to convert the keys into some ordered form. We can first append all the keys in the form of a list. Next, we can index the list to find the next key present. With the help of the key, we can also access the corresponding value

Syntax

<dictionary name>.keys()

The keys method is an in-built method of Python that returns the keys in the dictionary. It returns a view object which we can convert into a list using the list method of Python. The view object is dynamic; hence, any dictionary change will also be reflected in the view object.

<iterable object>.index(<name of the key>, start, end)

In Python, the "index" method is an in-built method. It can be applied to the iterable sequence. It takes one necessary parameter, namely the value whose index we need to find in the iterable sequence. Additionally, it takes two optional parameters, start and end, to define the range we need to find the element. It returns an integer representing the element's first occurrence in the iterable sequence.

Example

In the following code, we first created the dictionary named my_dict. We defined the current key to be 'banana'. In this case, we aim to find the next key, ' orange'. We used the keys method of dictionaries to get all the dictionary keys. Next, we used the index method to access the index of the current key. We provided a conditional statement where we have printed the key whose index is just one more than the current key.

my_dict = {'apple': 1, 'banana': 2, 'orange': 3, 'kiwi': 4}
current_key = 'banana'
keys = list(my_dict.keys())
current_index = keys.index(current_key)
print("The next element to banana is: ", end="")
if current_index < len(keys) - 1:
    next_key = keys[current_index + 1]
    print(next_key)  
else:
    print("No next key found.")

Output

The next element to banana is − orange

Use The OrderedDict Module

Another approach to obtaining the next key in a dictionary is using the Ordered Dict class from the collections module. The Ordered Dict allows us to create the dictionary and iterate through the items. However, the representation of the dictionary when using this module is quite different compared to the traditional dictionary. The items are taken in the form of Tuples.

Syntax

OrderedDict([(key1, value1), (key2, value2), (key3, value3), other key-value pairs.....])

Ordered Dict' is the class name of the ordered dictionary provided by Python's 'collections module. We need to pass all the key-value pairs as Tuple objects, and commas separate the Tuples objects. We can have multiple tuple objects, and this dictionary object is iterable.

Example

In this code, we first imported the Ordered Dict module from the collections library of Python. Next, we define our dictionary. Notice that the key-value pairs are separated by commas and enclosed with Tuples. Next, we set the flag of the variable found_current_key to false. We iterated through the dictionary and updated the value of the next_key variable. This variable contains our required result. Note that we have used the Ordered Dict; hence, the dictionary is now iterable.

from collections import OrderedDict
my_dict = OrderedDict([('apple', 1), ('banana', 2), ('orange', 3), ('kiwi', 4)])
current_key = 'orange'
next_key = None
found_current_key = False
print("The next element to banana is: ", end="")
for key in my_dict:
    if found_current_key:
        next_key = key
        break
    if key == current_key:
        found_current_key = True
print(next_key)  

Output

The next element to banana is: kiwi

Using the keys() method and a flag

If you don't need to maintain the order of keys, a simple approach is to use a dictionary's keys() method and a flag variable to track the current key. The idea is to iterate through the dictionary keys, and if the current key is found, then update the value of the next key. Note that if we use the keys method of Python, we get all the keys in the form of lists. The lists are iterable, and hence we can perform this iteration.

Example

In the following code, we created the dictionary and set the value of the current_key to "apple". Next, we set the value of the next_key variable to False. We iterated through the keys of the dictionary. We used a conditional statement. The conditional statement checks if the found_current_key flag is true and assigns the current key to the next_key if true, breaking the loop. If the current key equals the current_key, the found_current_key flag is true.

my_dict = {'apple': 1, 'banana': 2, 'orange': 3, 'kiwi': 4}
current_key = 'apple'
next_key = None
found_current_key = False
print("The next element to banana is: ", end="")
for key in my_dict.keys():
    if found_current_key:
        next_key = key
        break
    if key == current_key:
        found_current_key = True
print(next_key) 

Output

The next element to banana is: banana

Conclusion

In this article, we understood how to get the next key in the Dictionary in Python. We can utilize the iterative property of a list or Tuple to collect all the dictionary keys and find the next key available. Python also offers us the Ordered Dict module, which we can use to iterate through the dictionary items easily. The module provides us with the ability to create iterative dictionaries. Finally, we can utilize the key and the flag to achieve the same.

Updated on: 28-Jul-2023

776 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements