I provide an example class based on an OrderedDict — with an adjunct dictionary to index to the next and prev OrderedDict entry. In my case, I have a rather static OrderedDict: it is a dictionary of AISC shape objects. The function set_prev_next() must be called after each operation that modifies OrderedDict.
class MyClass(coll.OrderedDict):
mynpdict = {}
def __getitem__(self, key):
blah
blah
return coll.OrderedDict.__getitem__(self, key)
def set_prev_next(self):
# build a next/prev dict so that we may access previous shape and next shape
# mynpdict is the dict we are building
currp = curr = currn = None
for e in self:
self.mynpdict[curr] = (currp, currn)
currp, curr, currn = curr, currn, e
# now get the last entry in the OrderedDict
# tuple will be (prev, next)
self.mynpdict[curr] = (currp, currn)
def get_prev(self, q):
# tuple from dict mynpdict[q.upper()] is (prev, next)
# so [0] is the index for prev
# so [1] is the index for next
# upper(), because, in my case, the keys are all caps
try:
qn = self[self.mynpdict[q.upper()][0]]
except:
qn = None
return qn
def get_next(self, q):
# tuple from dict mynpdict[q.upper()] is (prev, next)
# so [0] is the index for prev
# so [1] is the index for next
# upper(), because, in my case, the keys are all caps
try:
qn = self[self.mynpdict[q.upper()][1]]
except:
qn = None
return qn
https://stackoverflow.com/questions/12328184/how-to-get-the-next-item-in-an-ordereddict#12329591