DEV Community

Cover image for Tip: You should use dict.get(key) instead of dict[key]
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

1

Tip: You should use dict.get(key) instead of dict[key]

A common debate among Python developers seems to stem from the retrieval of dictionary values, which can be accomplished using either dict[key] or dict.get(key).

Although you can achieve the same result using either one, dict.get() is usually preferred, as it accepts a second argument which acts as the default value shall the key not exist in the given dictionary. Due to this property, dict.get() will always return a value, whereas dict[key] will raise a KeyError if the given key is missing.

a = { 'max': 200 }
b = { 'min': 100, 'max': 250 }
c = { 'min': 50 }

a['min'] + b['min'] + c['min'] # throws KeyError
a.get('min', 0) + b.get('min', 0) + c.get('min', 0) # 150
Enter fullscreen mode Exit fullscreen mode

Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

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