DEV Community

Cover image for Getting values from a Python dictionary
Constantine
Constantine

Posted on

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.

Top comments (0)