On Tue, Oct 05, 2021 at 08:45:55AM +0100, Alex Waygood wrote: > I think there definitely should be a more obvious way to do this > (specifically the first and last keys/values/items of a dictionary
What's your use-case for caring what the first and last key in a dict is? > 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())[0] Example number 9758 of why not to trust everything you see on Stackoverflow :-) > 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())) Not every *one* line function needs to be a builtin. > But I think I like a lot more the idea of adding general ways of doing > these things to itertools. How about some recipes? `next(iter(mydict))` etc is a simple, easy, memorable, readable, maintainable way to get what you want. Composition of simple operations is great! Not everything needs to be a named function: def addone(x): """Return x + 1. >>> addone(32) 33 """ return x + 1 -- Steve _______________________________________________ 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/235UJMEIN64W2X7CNFIR3O6MXMPOQT2S/ Code of Conduct: http://python.org/psf/codeofconduct/