[Python-ideas] `OrderedDict.items().__getitem__`
Oscar Benjamin
oscar.j.benjamin at gmail.com
Thu Jan 16 11:53:42 CET 2014
On Sat, Jan 11, 2014 at 04:36:49PM +0100, Peter Otten wrote:
> Ram Rachum 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?
>
> I think an O(N) __getitem__() is even uglier. Also, you should have really
> compelling reasons for allowing the interfaces of dict.items() and
> OrderedDict.items() to diverge.
Agreed, but I do think that OrderedDict could be more helpful here. I haven't
wanted to get the first item before but I have wanted to get the last without
popping it off. Since this can be provided in O(1) I think it would make a
reasonable addition as a property of OrderedDict:
@property
def last(self):
if not self:
raise KEyError('dictionary is empty')
return self.__root.prev
Just returning the key sufficient but in my own use cases I would have wanted
the whole item which you could easily do:
@property
def lastitem(self):
if not self:
raise KEyError('dictionary is empty')
key = self.__root.prev
return key, self.__map[key]
Oscar
More information about the Python-ideas
mailing list