Have folks thought about allowing indexing dictionary views as in the
following code, where d is a dict object?
d.keys()[0]
d.keys()[-1]
d.values()[0]
d.values()[-1]
d.items()[0]
d.items()[-1] # item that would be returned by d.popitem()
I could see value to the last form in particular: you might want to inspect
the last item of a dictionary before possibly popping it.
I've also often wanted to get an arbitrary item/key from a dictionary, and
d.items()[0] seems natural for this. Of course, the universal way to get the
first item from an iterable x is
item = next(iter(x))
I can't say this is particularly readable, but it is functional and fast. Or
sometimes I use this pattern:
for item in x: break
If you wanted the last item of a dictionary d (the one to be returned from
d.popitem()), you could write this beautiful code:
last = next(iter(reversed(d.items())))
Given the dictionary order guarantee from Python 3.7, adding indexing
(__getitem__) to dict views seems natural. The potential catch is that (I
think) it would require linear time to access an item in the middle, because
you need to count the dummy elements. But accessing [i] and [-i] should be
doable in O(|i|) time. (I've wondered about the possibility of doing binary
or interpolation search, but without some stored index signposts, I don't
think it's possible.)
Python is also full of operations that take linear time to do: list.insert(0,
x), list.pop(0), list.index(), etc. But it may be that __getitem__ takes
constant time on all built-in data structures, and the apparent symmetry but
very different performance between dict()[i] and list()[i] might be confusing.
That said, I really just want d[0] and d[-1], which is when these are fast.
I found some related discussion in
https://mail.python.org/archives/list/python-ideas@python.org/thread/QVTGZD6USSC34D4IJG76UPKZRXBBB4MM/
but not this exact idea.
Erik
--
Erik Demaine | edema...@mit.edu | http://erikdemaine.org/
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/PPI747IBFYYRAVPUJDY4DKFNTJGASH3K/
Code of Conduct: http://python.org/psf/codeofconduct/