DEV Community

Paurakh Sharma Humagain
Paurakh Sharma Humagain

Posted on

4 2

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'

Top comments (2)

Collapse
 
thijs0x57 profile image
thijs0x57

I like it, very short and simple but clear. Thanks!

Collapse
 
paurakhsharma profile image
Paurakh Sharma Humagain

I am glad you liked it ☺️

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay