On Sat, Aug 1, 2020 at 12:40 PM Steven D'Aprano steve@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,