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

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Tue Jan 12 15:18:03 EST 2016


Marko Rauhamaa writes:

> Jussi Piitulainen:
>
>> But the most readable thing might be to have a function that extracts
>> the sole value by whatever means:
>>
>>    >>> def sole(d): [o] = d.values() ; return o
>>    ... 
>>    >>> sole(shoe)
>>    3.141592653589793
>
> In the same vein:
>
>    >>> def sole(d):
>    ...   for o in d.values():
>    ...     return o
>    ... 
>    >>> sole(shoe)
>    3.141592653589793

Tuple assignment has a useful side effect that all other methods present
in this thread lack: it raises an exception if the number of dictionary
entries is not exactly one.



More information about the Python-list mailing list