Skip to content
Advertisement

How can you slice with string keys instead of integers on a python OrderedDict?

Since an OrderedDict has the features of both a list (with ordered elements), and a dictionary (with keys instead of indexes), it would seem natural that you could slice using keys.

JavaScript

What’s interesting about this is that it’s not the error you’d see due to OrderedDictionary.__getslice__ not being implemented. I tried adding my own __getslice__ method to OrderedDict, but I keep running into this TypeError problem. It seems like Python is doing some kind of type checking to enforce that slice keys are only integers, before they even get passed to the __getslice__ function, how unpythonic!

JavaScript

So my question is, why can’t I implement non-int slices, what kind of type-checking is preventing the slice keys from even reaching my __getslice__ function, and can I override it by implementing my BetterOrderedDict in C with bindings?

Advertisement

Answer

__getslice__ is deprecated way of implementing slicing. Instead you should handle slice objects with __getitem__:

JavaScript

And if you need more than potato, than you can implement all three slicing operations following way:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement