Created
November 9, 2017 12:57
-
-
Save oscarcp/92a1bb3f0918bcc2bf81bacb084061ea to your computer and use it in GitHub Desktop.
Extended Dictionary class for searching keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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