As others have noted, Python dictionaries are inherently disordered. However, at any time, a list of their current keys or key pairs, values โโcan be obtained using the keys() or items() methods.
The potential problem with using these lists is that not only their contents, but also the order in which it is returned will probably change if the dictionary has been changed (or changed) since the last time it was used. This means that, as a rule, you cannot store and reuse a list if you do not update it every time the dictionary changes, in case you need it.
To make this approach more manageable, you can combine a dictionary and an auxiliary list into a new derived class that synchronizes between them, and also provides a get_range() method that uses the current contents of the list. The following is sample code showing how to do this. This is based on the ideas I got from the code in this ActiveState Python recipe .
class dict_with_get_range(dict): def __init__(self, *args, **kwrds): dict.__init__(self, *args, **kwrds) self._list_ok = False def _rebuild_list(self): self._list = [] for k,v in self.iteritems(): self._list.append((k,v)) self._list_ok = True def get_range(self, begin, end): if not self._list_ok: self._rebuild_list() return dict(self._list[i] for i in range(begin,end+1)) def _wrapMutatorMethod(methodname): _method = getattr(dict, methodname) def wrapper(self, *args, **kwrds):
The main idea is to derive a new class from dict , which also has a list of internal contents for use by the new get_range() method, which it provides that regular dictionary objects do not. To minimize the need to update (or even create) this internal list, it also has a flag indicating whether this list is updated or not, and only checks it and rebuilds the list when necessary.
To support the flag, each legacy dictionary method that potentially modifies (or alters) the contents of the dictionary is โwrappedโ by an auxiliary function, discards the flag, and then binds to standard dictionary methods for actual operation. Installing them in a class is simply a matter of entering the names of the methods in one of the two lists, and then transferring them to one auxiliary utility immediately after creating the class.