[Python-ideas] OrderedDict.peekitem()

Neil Girdhar mistersheik at gmail.com
Tue Jul 7 06:27:45 CEST 2015


On Tue, Jul 7, 2015 at 12:08 AM, Andrew Barnert <abarnert at yahoo.com> wrote:

> On Jul 6, 2015, at 14:30, Neil Girdhar <mistersheik at gmail.com> wrote:
>
> SortedDict (
> http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html) manages
> to support indexing.
>
>
> Only by having a special view, accessed as .index. If it just took indices
> as subscripts, that would be ambiguous with integer keys.
>
> Can OrderedDict do the same thing?
>
>
> It's worth noting that most of the various different sorted containers on
> PyPI support something equivalent, but all with different interfaces.
>

2015 might not be the right year to add sorted containers to Python.
However, it might be a good idea to standardize the interface of a "sorted
map" and "sorted set" in a PEP.


>
> More importantly, they all use logarithmic data structures (binary trees,
> b-trees, skip lists, the hybrid thing blist uses, ...), which give you
> O(log N) indexing, and some of them can do even better by giving you O(log
> N) to find a slice and O(1) within that slice; OrderedDict uses a linked
> list, so it would be O(N).
>
>
> On Monday, July 6, 2015 at 10:49:44 AM UTC-4, Kale Kundert wrote:
>>
>> Today I was trying to use collections.OrderedDict to manage a LIFO queue,
>> and I
>> was surprised to realize that OrderedDict doesn't provide a way to look
>> at its
>> first or last item.  There is an OrderedDict.popitem() method, which
>> removes and
>> returns either the first or last item, but it's not hard to imagine cases
>> where
>> you would want to see what's on the queue without popping it right away.
>>
>> My proposal is to add a peekitem() method to OrderedDict.  This method
>> would
>> have the same signature and would return the same thing as popitem(), it
>> just
>> wouldn't modify the data structure.
>>
>> -Kale
>>
>> P.S. There is already a way to peek at the last item an OrderedDict, but
>> it
>> hides the intent of the code and you wouldn't think of it if you weren't
>> familiar with python: next(reversed(ordered_dict))
>>
>> _______________________________________________
>> Python-ideas mailing list
>> Python... at python.org
>> https://mail.python.org/mailman/listinfo/python-ideas
>> Code of Conduct: http://python.org/psf/codeofconduct/
>>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150707/11a7278a/attachment-0001.html>


More information about the Python-ideas mailing list