Skip to content

Instantly share code, notes, and snippets.

@oscarcp
Created November 9, 2017 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oscarcp/92a1bb3f0918bcc2bf81bacb084061ea to your computer and use it in GitHub Desktop.
Save oscarcp/92a1bb3f0918bcc2bf81bacb084061ea to your computer and use it in GitHub Desktop.
Extended Dictionary class for searching keys
class ExtendedOrderedDict(OrderedDict):
"""Extended version of the OrderedDict with more methods.
This class adds the 'next_key' and 'first_key' to easily traverse through
an ordered dictionary. It's meant to be inherited by any OrderedDict
structure.
"""
def get_next_key(self, key):
key_list = list(self.keys())
key_position = key_list.index(key)
if key_position < len(key_list) - 1:
return key_list[key_position + 1]
else:
raise IndexError("{} is already the last key.".format(key_position))
def get_previous_key(self, key):
key_list = list(self.keys())
key_position = key_list.index(key)
if key_position > 0:
return key_list[key_position - 1]
else:
raise IndexError("{} is already the first key.".format(key_position))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment