Stop Using dict[key] to Access Values in Python Dictionaries!
<p>We probably learnt to use <code>dict[key]</code> to access a value in a dictionary at the start. But here’s a better way to do that.</p>
<h1>The original dict[key] method</h1>
<pre>
d = {'apple':4, 'orange':5, 'pear':6}
x = d['apple'] # 4
y = d['orange'] # 5
z = d['pear'] # 6</pre>
<p>We use <code>d[key]</code> to access the value of <code>key</code> in a dictionary <code>d</code>.</p>
<pre>
a = d['pineapple'] # KeyError</pre>
<p>However, if a key doesn’t exist in the dictionary, the <code>d[key]</code> raises a KeyError, which crashes our Python script. Which can get really annoying quickly.</p>
<h1>A Sad True Story</h1>
<p>So I was running a web scraping script a couple years ago.</p>
<p>Estimated time of completion: Overnight (many many pages)</p>
<p>So I went to sleep, hoping it’ll be done by tomorrow.</p>
<p> </p>
<p>It crashed due to a KeyError</p>
<p>The KeyError was from some dumb unimportant part with <code>dict[key]</code></p>
<p>I just wasted 8 hours of my life due to <code>dict[key]</code></p>
<p><a href="https://levelup.gitconnected.com/stop-using-dict-key-to-access-values-in-python-dictionaries-7ab45bb7946c">Website</a></p>