[Python-ideas] `OrderedDict.items().__getitem__`
Mathias Panzenböck
grosser.meister.morti at gmx.net
Sat Jan 11 22:47:26 CET 2014
Why not:
get_first = lambda d: next(iter(d.items()))
No need for a full copy of the dict.
On 01/11/2014 09:51 PM, Ryan Gonzalez wrote:
> 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 <mailto:rosuav at gmail.com>> wrote:
>
> On Sun, Jan 12, 2014 at 1:18 AM, Ram Rachum <ram.rachum at gmail.com <mailto: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 <mailto: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.
>
>
> _______________________________________________
> 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/
>
More information about the Python-ideas
mailing list