Stop Using dict[key] to Access Values in Python Dictionaries!

<p>We probably learnt to use&nbsp;<code>dict[key]</code>&nbsp;to access a value in a dictionary at the start. But here&rsquo;s a better way to do that.</p> <h1>The original dict[key] method</h1> <pre> d = {&#39;apple&#39;:4, &#39;orange&#39;:5, &#39;pear&#39;:6} x = d[&#39;apple&#39;] # 4 y = d[&#39;orange&#39;] # 5 z = d[&#39;pear&#39;] # 6</pre> <p>We use&nbsp;<code>d[key]</code>&nbsp;to access the value of&nbsp;<code>key</code>&nbsp;in a dictionary&nbsp;<code>d</code>.</p> <pre> a = d[&#39;pineapple&#39;] # KeyError</pre> <p>However, if a key doesn&rsquo;t exist in the dictionary, the&nbsp;<code>d[key]</code>&nbsp;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&rsquo;ll be done by tomorrow.</p> <p>&nbsp;</p> <p>It crashed due to a KeyError</p> <p>The KeyError was from some dumb unimportant part with&nbsp;<code>dict[key]</code></p> <p>I just wasted 8 hours of my life due to&nbsp;<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>