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}
What will happen if you get a value from this dictionary by slicing?
donuts['vanilla']
1
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'
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
Even more, you can provide a default value, if that is what you need:
donuts.get('blueberry', 0)
0
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)