Beginner Python tips Day - 02 dict.get()

paurakhsharma

Paurakh Sharma Humagain

Posted on June 5, 2020

Beginner Python tips Day - 02 dict.get()
# Day-02 dict .get()

my_dict = {'hello': 'world'}

try:
    my_dict['world']
    # Throws KeyError exception
except KeyError:
    print('Cannot find the provided key in the dictionary')

# Use .get() to be safe from the exception
print(my_dict.get('world'))
# prints None in the console

# You can pass second argument as default value
print(my_dict.get('world', 'default value'))
# prints 'default value'
💖 💪 🙅 🚩
paurakhsharma
Paurakh Sharma Humagain

Posted on June 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related