subscripting Python 3 dicts/getting the only value in a Python 3 dict
Peter Otten
__peter__ at web.de
Tue Jan 12 13:09:29 EST 2016
Ian Kelly wrote:
> On Tue, Jan 12, 2016 at 10:12 AM, Terry Reedy <tjreedy at udel.edu> wrote:
>> Using the values views at intended (as an iterable):
>>
>>>>> dv = d.values()
>>>>> next(iter(dv))
>> 1
>
> Good coding practice also dictates that whenever next is called, the
> potential StopIteration exception must be caught unless it is clearly
> intended to be propagated up to some generator.
Even then you should be prepared for
https://docs.python.org/dev/whatsnew/3.5.html#pep-479-change-stopiteration-handling-inside-generators
> So more fully, this
> should be something like:
>
> dv = iter(d.values())
> try:
> next(dv)
> except StopIteration:
> raise IndexError("d is empty")
>
> At which point it may be desirable to extract that into a utility
> function.
More information about the Python-list
mailing list