On Sat, Aug 1, 2020 at 12:40 PM Steven D'Aprano <st...@pearwood.info> wrote: > > On Fri, Jul 31, 2020 at 08:08:58PM -0700, Guido van Rossum wrote: > > > > The other simple solution is `next(iter(mydict.items()))`. > > > > > > > That one always makes me uncomfortable, because the StopIteration it raises > > when the dict is empty might be misinterpreted. Basically I never want to > > call next() unless there's a try...except StopIteration: around it, and > > that makes this a lot less simple. > > Acknowledged. But there are ways to solve that which perhaps aren't as > well known as they should be. > > * Use a default: `next(iter(mydict.items()), MISSING)` > > * Use a helper to convert StopIteration to something else. >
There is a most simple solution: * `[first] = mydict.items()`, or `first, = mydict.items()` Anyway, should we add some tools to itertools, instead of "itertools recipe"? * `first(iterable, default=None)` -- same to `[first] = iterable`, but return default value instead of ValueError when iterable is empty. * `nth(iterable, n, default=None)` * `consume(iterator, n=None)` Regards, -- Inada Naoki <songofaca...@gmail.com> _______________________________________________ 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/75EFRNZQS7FZWVS5BL2RZ73QKA3D4NZR/ Code of Conduct: http://python.org/psf/codeofconduct/