[Python-ideas] `OrderedDict.items().__getitem__`

Ryan Gonzalez rymg19 at gmail.com
Sat Jan 11 21:51:28 CET 2014


Based on your popitem idea:

get_first = lambda d: d.copy().popitem()
get_last = lambda d: d.copy().popitem(last=True)



On Sat, Jan 11, 2014 at 8:36 AM, Chris Angelico <rosuav at gmail.com> wrote:

> On Sun, Jan 12, 2014 at 1:18 AM, Ram Rachum <ram.rachum at gmail.com> wrote:
> > I think that `OrderedDict.items().__getitem__` should be implemented, to
> > solve this ugliness:
> >
> >
> http://stackoverflow.com/questions/21062781/shortest-way-to-get-first-item-of-ordereddict-in-python-3
> >
> > What do you think?
>
> Well, the first problem with that is that __getitem__ already exists,
> and it's dict-style :) So you can't fetch out an item by its position
> that way. But suppose you create a method that returns the Nth
> element.
>
> The implementation in CPython 3.4 is a linked list, so getting an
> arbitrary element by index would be quite inefficient. Getting
> specifically the first can be done either with what you see in that
> link (it could be made a tiny bit shorter, but not much), but anything
> else would effectively entail iterating over the whole thing until you
> get to that position, so you may as well do that explicitly.
> Alternatively, if you're okay with it being a destructive operation,
> you can use popitem() to snag the first (or last, if you wish)
> key/value pair.
>
> ChrisA
> _______________________________________________
> 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/
>



-- 
Ryan
When your hammer is C++, everything begins to look like a thumb.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140111/cb1808ff/attachment.html>


More information about the Python-ideas mailing list