Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the next key in order of dictionary. This can have application as from Python 3.6 onwards the dictionaries are ordered. Lets discuss certain ways in which this task can be performed.
Method #1 : Using index() + loop (O (n))
The combination of above functions can be used to perform this task. In this, we perform the conversion of dictionary elements to list. And then index() is used to check for index and append the index count to get the next item.
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 }
print ( "The original dictionary is : " + str (test_dict))
test_key = 'is'
temp = list (test_dict)
try :
res = temp[temp.index(test_key) + 1 ]
except (ValueError, IndexError):
res = None
print ( "The next key is : " + str (res))
|
Output : The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2}
The next key is : best
Method #2 : Using iter() + next() (O (n))
This is yet another way in which this task can be performed. In this, we convert the dictionary to iterator using iter() and then extract the next key using next().
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 }
print ( "The original dictionary is : " + str (test_dict))
test_key = 'is'
res = None
temp = iter (test_dict)
for key in temp:
if key = = test_key:
res = next (temp, None )
print ( "The next key is : " + str (res))
|
Output : The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2}
The next key is : best
Method #3 : If you have lots of queries, they should be fast -> (O (1))
Create two additional dictionaries “index_of_key” and “key_of_index” in O (n). Then it is easy finding an index of any key of original dictionary and choose any other plus or minus this, check if it is in dictionary “key_of_index” and if, then get it.
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 }
ki = dict ()
ik = dict ()
for i, k in enumerate (test_dict):
ki[k] = i
ik[i] = k
print ( "The original dictionary is:" , test_dict)
test_key = 'is'
offset = 1
index_of_test_key = ki[ 'is' ]
index_of_next_key = index_of_test_key + offset
res = ik[index_of_next_key] if index_of_next_key in ik else None
print ( "The next key is:" , res)
|
Output :
The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2}
The next key is : best