DEV Community

Cover image for Getting values from a Python dictionary
Constantine
Constantine

Posted on

4 1

Getting values from a Python dictionary

How to get a value from a Python dictionary and not get punched by a KeyError

Photo by Sharon McCutcheon on Unsplash

Let's say you have some dictionary with donuts:

donuts = {'vanilla': 1, 'chocolate': 2}
Enter fullscreen mode Exit fullscreen mode

What will happen if you get a value from this dictionary by slicing?

donuts['vanilla']
1
Enter fullscreen mode Exit fullscreen mode

But what if dictionary doesn't have such a key?

donuts['blueberry']
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'blueberry'
Enter fullscreen mode Exit fullscreen mode

A KeyError exception…

So, to gracefully get a value from a dictionary you might want to use a get() method:

donuts.get('vanilla')
1

donuts.get('blueberry')
None
Enter fullscreen mode Exit fullscreen mode

Even more, you can provide a default value, if that is what you need:

donuts.get('blueberry', 0)
0
Enter fullscreen mode Exit fullscreen mode

I'm not saying you should never use slicing when accessing dictionary values.
If you 100% sure the key is present then why not?
Otherwise use get(), it might save you a ton of time later.

And even more advanced topic would be defaultdict from the collections module. When you can assign a value to a key if that key doesn't exist.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay