I think there definitely should be a more obvious way to do this (specifically the first and last keys/values/items of a dictionary — I'm ambivalent about the others, since they won't always be fast, as discussed). An anti-pattern you see quite often on Stack Overflow to get the first key of a dictionary is something like the following:
first_key = list(mydict.keys())
Whereas obviously, a much better way (especially if it's a very large dictionary) is to do:
first_key = next(iter(mydict))
I'll leave it exercise for the reader to find that thead
For reference, the (very long) previous thread is here: https://firstname.lastname@example.org/thread/S7UMTWK....
I think we can add `itertools.first()` for this idiom, and `itertools.last()` for `next(iter(reversed(x)))` idiom.
I like this idea, a lot. Another possibility I've been wondering about was whether several methods should be added to the dict interface: dict.first_key = lambda self: next(iter(self)) dict.first_val = lambda self: next(iter(self.values())) dict.first_item = lambda self: next(iter(self.items())) dict.last_key = lambda self: next(reversed(self)) dict.last_val = lambda self: next(reversed(self.values())) dict.last_item = lambda self: next(reversed(self.items())) But I think I like a lot more the idea of adding general ways of doing these things to itertools.
Have folks thought about allowing indexing dictionary views as in the following code, where d is a dict object?
d.keys() d.keys()[-1] d.values() d.values()[-1] d.items() d.items()[-1] # item that would be returned by d.popitem()
since dicts were made order-preserving, indexing the keys, items, etc does make some sense.
I've also often wanted to get an arbitrary item/key from a dictionary, and
This is indeed one of the use cases identified.
I found some related discussion in https://email@example.com/thread/QVTGZD6... but not this exact idea.
That's a pretty different idea but this exact idea has been discussed on this list relatively recently. I still like it, but there wan't much general support.
I'll leave it exercise for the read to find that thead, but it is there, and I suggest you look for it if you want to further pursue this idea.
-- Christopher Barker, PhD (Chris)
Python Language Consulting
- Scientific Software Development
- Desktop GUI and Web Development
- wxPython, numpy, scipy, Cython
Python-ideas mailing list -- firstname.lastname@example.org To unsubscribe send an email to email@example.com https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://firstname.lastname@example.org/message/RAEDZP... Code of Conduct: http://python.org/psf/codeofconduct/