Roy Smith <[EMAIL PROTECTED]> writes:

> Greg Ewing <[EMAIL PROTECTED]> 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']
> ---------------

I couldn't resist:

py> d = slicableDict()
py> d[3j] = 1
py> d[4j] = 2
py> d[5j] = 3
py> d[6j] = 4
py> d[4j:5j]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in __getitem__
TypeError: cannot compare complex numbers using <, <=, >, >=

Somehow, that seems like a wart.

         <mike
-- 
Mike Meyer <[EMAIL PROTECTED]>                  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to