How to get a false-like value instead of error when retrieving non-existent elements in lists or dictionaries in Python

Viewed 57

I would like to know how to, instead of getting an error, return a False-like value when trying to access a list out of range, for example, or trying to grab a key from a dictionary that doesn't exist. Does anyone know of a method?

3 Answers

Dictionaries have a get method allowing you to do exactly that

test = {}
test.get("gold", False)

this yields False or anything else that you give get as a 2nd argument.

When you try to access a list out of range, you get this message on the last line of the console logs:

IndexError: list index out of range

so, to take an example:

test_list = [0]*1

print(test_list[1])

IndexError: list index out of range

So you need:

test_list = [0]*1

try:
   print(test_list[1])
except IndexError:
   value = False
   print (value)

False

for a dictionary you can use a defaultdict from the collections module I.E:

from collections import defaultdict

my_dict = defaultdict(lambda: False)

my_dict['test']  # This will be False

You can read more about defaultdict in the docs

For a list however it gets a bit more complicated, sublcassing list and overriding the __getitem__ method to wrap the call in a try/except clause and return a different value:

class defaultlist(list):
    def __getitem__(self, key):
        try:
            return super().__getitem__(key)
        except IndexError:
            return False

my_list = defaultlist()
my_list[10]  # This will be False
Related