Search code examples
pythonsorteddictionary

Iterate over a slice of items in a SortedDict?


I would like to iterate over a slice of items in a sortedcontainers SortedDict. I know that I can do something like this:

from sortedcontainers import SortedDict

d = SortedDict(b=20, d=30, c=10, e=50, a=40)

print [k, d[k] for k in in d.islice(1, 4)]
>> [('b', 20), ('c', 10), ('d', 30)]

but I'd like to avoid all of the individual d[k] lookups if possible; something like d.iteritems() that allows for a slice:

for k, v in d.islice_items(1, 4):
    print k, v

Is there any way to iterate over a slice of items in a SortedDict?


Solution

  • As of v1.4.3 there isn't. The rationale is two fold:

    1. Lookups are just so friggin fast.
    2. In the implementation, SortedDict inherits directly from dict. So the values themselves are stored in the dict and SortedDict has no way to get at them than to do the lookup itself.

    If we added an isliceitems method it would do the same as you're doing.

    You might try:

    lookup = dict.__getitem__
    print [k, lookup(d, k) for k in in d.islice(1, 4)]
    

    But I would hope that's not faster.