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

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Fri Apr 22 09:42:41 EDT 2005


Roy Smith wrote:

> 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)
[...]

> 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.

Other possibility, probably faster when almost all keys in the range are in
the dictionary:

class sdict(dict):
    def __getitem__(self, index):
        if isinstance(index, slice):
            d = {}
            for key in xrange(slice.start, slice.stop, slice.step):
                if key in self:
                    d[key] = self[key]
            return d
        else:
            return dict.__getitem__(self, index)

Reinhold



More information about the Python-list mailing list