[Python-ideas] OrderedDict.peekitem()

Andrew Barnert abarnert at yahoo.com
Mon Jul 6 22:39:35 CEST 2015

On Jul 6, 2015, at 07:56, Todd <toddrjen at gmail.com> wrote:
> On Jul 6, 2015 4:49 PM, "Kale Kundert" <kale at thekunderts.net> 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))
> What about just making OrderedDict.values support indexing?
Then you can't use integers as keys.

Also, would a novice really expect d[0] to return an item (key, value pair) rather than a value?

I think this pretty much has to be a nonstandard function, not an ambiguous reuse of subscripting.

Or, maybe better, OrderedDict could have extended keys/values/items views that return something that's tuple-like as well as set-like (because indexing doesn't have any meaning on the standard views to conflict with, and nobody would expect mutability, and it would be obvious whether you're getting keys, values, or items).

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150706/1ead7d9e/attachment-0001.html>

More information about the Python-ideas mailing list