[Python-ideas] OrderedDict.peekitem()

Steven D'Aprano steve at pearwood.info
Tue Jul 7 14:34:06 CEST 2015

On Tue, Jul 07, 2015 at 12:59:07AM -0700, Kale Kundert wrote:

> On 07/06/2015 11:59 PM, Neil Girdhar wrote:
> > What's wrong with "next(iter(o))" and "next(reversed(o))"?
> Three things:
> 1. Someone who is not all that familiar with python would never think to do
> either of those things.  I've been using python for years and it didn't occur to
> me that I could peek at the ends of an OrderedDict like that until I saw someone
> on stack overflow suggest it.
> 2. Furthermore, if you don't have a good understanding of iterators in python,
> you could be excused for thinking that 'next(reversed(o))' creates a temporary
> list and is O(n) in time and memory.  Those expressions read like they're doing
> a lot more work than they actually are, and that's confusing.

Do we know that OrderedDict.__reversed__ *doesn't* do that? I assume it 
won't, but I'm not sure it's a guarantee.

> 3. Readability counts, and those expressions hide the intent of the programmer.
>  You wouldn't use 'next(iter(o))' to access the first element of a list, because
> that would be confusing and obfuscated.

I agree with all of those objections, especially the third. Which is why 
the reasonable and simple solution is to write:

def first(od):
    return next(iter(od))

def last(od):
    return next(reversed(od))

then call first(o), last(o). Add comments, documentation and tests to 
taste. Or subclass OrderedDict and add first() last() methods.

I am unconvinced that peeking at the first and last items of a dict 
(ordered, sorted or otherwise), let alone O(1) indexed access to items, 
is a good fit for the OrderedDict API. If I were the OD maintainer, I 
would want to understand your use-case (why are you using an OD as a 
queue, instead of a list, deque, or queue?), and possibly hear two or 
three additional uses, before agreeing to add it to the API.


More information about the Python-ideas mailing list