VOOZH about

URL: https://www.geeksforgeeks.org/python/python-get-next-key-in-dictionary/

⇱ Get Next Key in Dictionary - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get Next Key in Dictionary - Python

Last Updated : 12 Jul, 2025

We are given a dictionary and need to find the next key after a given key, this can be useful when iterating over dictionaries or accessing elements in a specific order. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} if the current key is "b" then the next key should be "c". Now, let's explore different ways to achieve this in Python:

Using iter() and next()

We can use the iter() function to create an iterator over dictionary keys and the next() function to find the next key after a given key.


Output
c

Explanation:

  • iter(data) creates an iterator over dictionary keys, then the loop finds curr_key and next(keys_iter, None) retrieves the next key.
  • If curr_key is the last key, it returns None.

Using zip()

We can pair the adjacent dictionary keys using zip() and find the next key efficiently.


Output
c

Explanation:

  • zip(data, list(data)[1:]) pairs each key with its next key.
  • We iterate through these pairs and check if k1 matches curr_key and if a match is found, k2 is the next key.
  • If curr_key is the last key, nxt_key remains None.

Using list() and Indexing

We can convert dictionary keys into a list and use indexing to find the next key.


Output
c

Explanation:

  • list(data) converts the dictionary keys into a list and keys.index(curr_key) finds the index of curr_key.
  • keys[idx + 1] gets the next key or None if curr_key is the last key.
Comment