Slice equivalent to dict.get

Zachary Ware zachary.ware+pylist at gmail.com
Thu Mar 31 15:28:47 EDT 2016


On Thu, Mar 31, 2016 at 12:51 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> On 3/31/2016 11:24 AM, Peter Otten wrote:
>> try...except to the rescue:
>>
>>>>> def get(seq, index, default=None):
>>
>> ...     try: return seq[index]
>> ...     except IndexError: return default
>
>
> Replace IndexError with (IndexError, KeyError) and the functions works with
> any subscriptable that raises either exception.

Or use the superclass of both of those, LookupError, and also catch
anything that uses that more generic name as well.

-- 
Zach



More information about the Python-list mailing list