Why Python does *SLICING* the way it does??

Roy Smith roy at panix.com
Thu Apr 21 22:17:25 EDT 2005


Greg Ewing <greg at cosc.canterbury.ac.nz> wrote:
> Also, everyone, please keep in mind that you always have
> the option of using a *dictionary*, in which case your
> indices can start wherever you want.
> 
> You can't slice them, true, but you can't have everything. :-)

Of course you can slice them, you just have to subclass dict!  The 
following was about 15 minutes work:

---------------
import types

class slicableDict (dict):
    def __getitem__ (self, index):
        if type (index) == types.SliceType:
            d2 = slicableDict()
            for key in self.keys():
                if key >= index.start and key < index.stop:
                    d2[key] = self[key]
            return d2
        else:
            return dict.__getitem__ (self, index)

d = slicableDict()
d['hen'] = 1
d['ducks'] = 2
d['geese'] = 3
d['oysters'] = 4
d['porpoises'] = 5

print d
print d['a':'m']
---------------

Roy-Smiths-Computer:play$ ./slice.py
{'oysters': 4, 'hen': 1, 'porpoises': 5, 'geese': 3, 'ducks': 2}
{'hen': 1, 'geese': 3, 'ducks': 2}

I defined d[x:y] as returning a new dictionary which contains those items 
from the original whose keys are in the range x <= key < y.  I'm not sure 
this is terribly useful but it's a neat demonstration of just how simple 
Python makes it to do stuff like this.  I can't imagine how much work it 
would be to add a similar functionality to something like C++ multimap.

I'm sure the code above could be improved, and I know I've ignored all 
sorts of things like steps, and error checking.  Frankly, I'm amazed this 
worked at all; I expected to get a syntax error when I tried to create a 
slice with non-numeric values.

PS: Extra credit if you can identify the set of keys I used without 
resorting to google :-)



More information about the Python-list mailing list