Slice equivalent to dict.get

Sven R. Kunze srkunze at mail.de
Thu Mar 31 12:05:44 EDT 2016


On 31.03.2016 17:07, Steven D'Aprano wrote:
> Sometimes people look for a method which is equivalent to dict.get, where
> they can set a default value for when the key isn't found:
>
>
> py> d = {1: 'a', 2: 'b'}
> py> d.get(999, '?')
> '?'
>
>
> The equivalent for sequences such as lists and tuples is a slice. If the
> slice is out of range, Python returns a empty sequence:

I see what you are trying to achieve here. What do you think about this?

[1, 2, 3].get(999, '?')


Best,
Sven



More information about the Python-list mailing list