DEV Community

Waylon Walker
Waylon Walker

Posted on • Originally published at waylonwalker.com

3 1

python dict get

For an embarrassingly long time, til today, I have been wrapping my dict gets with key errors in python. I'm sure I've read it in code a bunch of times, but just brushed over why you would use get. That is until I read a bunch of PR's from my buddy Nic and notice that he never gets things with brackets and always with .get. This turns out so much cleaner to create a default case than try except.

Example

Lets consider this example for prices of supplies. Here we set a variable of prices as a dictionary of items and thier price.

prices = {'pen': 1.2, 'pencil', 0.3, 'eraser', 2.3}
Enter fullscreen mode Exit fullscreen mode

Except KeyError

What I would always do is try to get the key, and if it failed on KeyError, I would set the value (paper_price in this case) to a default value.

try:
    paper_price = prices['paper']
except KeyError:
    paper_price = None
Enter fullscreen mode Exit fullscreen mode

.get

What I noticed Nic does is to use get. This feels just so much cleaner that it's a one liner and feels much easier to read and understand that if there is no price for paper we set it to None.

paper_price = prices.get('paper', None)
Enter fullscreen mode Exit fullscreen mode

We can just as easily set the default to other values. Let's consider sales for instance. If there is not a record for the sale of paper, it might be that we sold 0 paper in the given dataset.

paper_sales = sales.get('paper', 0)
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay