Indexable dict and set (was: OrderedDict.peekitem())

If you want a `dict` or `set` that is indexable, it's quite easy using the sortedcontainers module. Just use the hash function as the key: ```python from sortedcontainers import SortedDict, SortedSet class DictWithIndex(SortedDict): def __init__(self, *args, **kwargs): super(DictWithIndex, self).__init__(hash, *args, **kwargs) class SetWithIndex(SortedSet): def __init__(self, *args, **kwargs): super(SetWithIndex, self).__init__(*args, key=hash, **kwargs) ``` The ordering can be quasi-random but the indexing can still be useful. Example usage: ``` In [2]: d = DictWithIndex(enumerate('abcde')) In [3]: d.iloc[4] Out[3]: 4 In [4]: d.iloc[-2] Out[4]: 3 In [5]: s = SetWithIndex('abcde') In [6]: s[4] Out[6]: 'e' In [7]: s[-2] Out[7]: 'd' ``` The likelihood that the hash collides is low and when it does so, the order will be based on insertion order.
participants (1)
-
Grant Jenks