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

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

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post