Stop Using dict[key] to Access Values in Python Dictionaries!
# Reducing the chance of crashing your Python script

We probably learnt to use dict[key] to access a value in a dictionary at the start. But here’s a better way to do that.
The original dict[key] method
d = {'apple':4, 'orange':5, 'pear':6}
x = d['apple'] # 4
y = d['orange'] # 5
z = d['pear'] # 6We use d[key] to access the value of key in a dictionary d.
a = d['pineapple'] # KeyErrorHowever, if a key doesn’t exist in the dictionary, the d[key] raises a KeyError, which crashes our Python script. Which can get really annoying quickly.
A Sad True Story
So I was running a web scraping script a couple years ago.
Estimated time of completion: Overnight (many many pages)
So I went to sleep, hoping it’ll be done by tomorrow.
It crashed due to a KeyError
The KeyError was from some dumb unimportant part with dict[key]
I just wasted 8 hours of my life due to dict[key]
Using dict.get(key) instead!!
d = {'apple':4, 'orange':5, 'pear':6}
x = d.get('apple') # 4
y = d.get('orange') # 5
z = d.get('pear') # 6
a = d.get('pineapple') # NoneWhen we use dict.get(key) instead of dict[key]:
- they have the same behaviour if the key exists in the dictionary
dict[key]raises a KeyError if the key doesn’t exist. Code crashes.dict.get(key)returnsNoneif the key doesn’t exist. No crashes.
Or use dict.get(key, defaultValue)
Use if you want to set a default value instead of None
d = {'apple':4}
x = d.get('apple') # 4
y = d.get('orange', 100) # 100
z = d.get('pear', 3.14159) # 3.14159When we use dict.get(key, defaultValue)
- if
keyexists, the actual value will be returned - if
keydoesn’t exist,defaultValuewill be returned
Conclusion
Hopefully this was helpful!
Some Final words
If this story was helpful and you wish to show a little support, you could:
- Clap 50 times for this story (this really, really helps me out)
- Sign up for a Medium membership using my link ($5/month to read unlimited Medium stories)
- Leave a comment telling me what you think!
My Ebooks: https://zlliu.co/ebooks
My LinkedIn: https://www.linkedin.com/in/zlliu/
