Python Dictionaries and the Good Old Square Notation
Python is the data scientists, data analysts and data engineers language of choice. That statement stirs up a debate as some of you would argue that R is the choice. I will not engage in that debate but instead would state the same statement hands down. I don't consider myself an expert in coding with Python. I just have enough knowledge to code, do it fast enough, debug it fast enough and be efficient at it.
That efficiency is what I am about to outline here. A lot of training materials talk about the Python dictionary data type. And the way to access data or should I say "values" in the Pythonic slang, is the good old square notation (e.g. foo = dictionary['bar']). This is well discussed and well covered. And is not wrong. But it is not efficient.
The better and more efficient way to access values with its keys is to use the dictionary method called ".get". I will get to the meat of the topic before this post gets TL;DR.
Given an empty dictionary: book = {}, to check if the key "author" exists without error is to use the try and except method.
Otherwise, without using the try and except method would result to a "KeyError".
Clearly, there should be a more efficient code than this. And yes there is -- the .get method.
The coding dilemma will only manifest itself if you are checking for a key that may or may not exist, and you will not want the code to stop the minute it doesn't. The try and except method will work. And again is not wrong.
But clearly the .get method is cleaner, more efficient way to access the key-value pairs of Python dictionaries. This is just my opinion, but sharing this tip might make coding more efficient for you. It took me a while to get used to it, but the change has made an impact in the way I code. Did it make me better? I will not answer. Rather, I invite you to try it out and you can answer for yourself right after.
Should you want to take a look at Python online course suggestions, I have compiled a list of courses from Udemy: Useful Python and Non-Python Trainings.