Why Python does *SLICING* the way it does??
Roy Smith
roy at panix.com
Fri Apr 22 10:51:56 EDT 2005
In article <3csdegF6p6jpnU1 at individual.net>,
Reinhold Birkenfeld <reinhold-birkenfeld-nospam at wolke7.net> wrote:
>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)
The problem with that is it requires the keys to be integers.
More information about the Python-list
mailing list