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

Chris Angelico rosuav at gmail.com
Sat Jan 11 15:36:11 CET 2014


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


More information about the Python-ideas mailing list