subscripting Python 3 dicts/getting the only value in a Python 3 dict

Ian Kelly ian.g.kelly at gmail.com
Tue Jan 12 12:39:55 EST 2016


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. 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