
[Steven D'Aprano <steve@pearwood.info>]
.... The other simple solution is `next(iter(mydict.items()))`.
[Guido]
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.
Last time this came up, this appeared to reach near-consensus: """ exactly what more-itertools has supplied for years already :-) If the iterable is empty/exhausted, by default ValueError is raised, but that can be overridden by also passing an optional argument to return instead (like dict.pop() in this respect). So, e.g., first([42]) returns 42 first([]) raises ValueError first([], 42) and first([], default=42) return 42 I don't think it belongs in the builtins. It doesn't perfectly fit anywhere, but given its prior history in the more-itertools and itertoolz packages, Python's itertools package seems the least annoying ;-) home for it. |"""