The Right Way to Access a Dictionary | by Radian Krisno | Towards Data Science

The dictionary is one of the data structures that are ready to use when programming in Python.
Dictionary is an unordered and unordered Python collection that maps unique keys to some values. In Python, dictionaries are written by using curly brackets {} . The key is separated from the key by a colon : and every key-value pair is separated by a comma ,. Here’s how dictionaries are declared in Python.
#A dictionary containing basketball players with their heights in mplayersHeight = {"Lebron James": 2.06,                 "Kevin Durant": 2.08,                  "Luka Doncic": 2.01,                 "James Harden": 1.96}
We have created the dictionary, however, what’s good about it if we cannot retrieve the data again right? This is where a lot of people do it wrong. I should admit, I was among them not long ago. After I realize the advantage, I never turn back even once. That’s why I am motivated to share it with you guys.
The well-known, or I should say the traditional way to access a value in a dictionary is by referring to its key name, inside a square bracket.
print(playersHeight["Lebron James"]) #print 2.06print(playersHeight["Kevin Durant"]) #print 2.08print(playersHeight["Luka Doncic"]) #print 2.01print(playersHeight["James Harden"]) #print 1.96
Everything seems OK, right? Not so fast! What do you think will happen if you type a basketball player’s name that is not in the dictionary? Look closely
playersHeight["Kyrie Irving"] #KeyError 'Kyrie Irving'
Notice that when you want to access the value of the key that doesn’t exist in the dictionary will result in a KeyError. This could quickly escalate into a major problem, especially when you are building a huge project. Fret not! There are certainly one or two ways to go around this.
Using If
if "Kyrie Irving" is in playersHeight:    print(playersHeight["Kyrie Irving"])
Using Try-Except
try:    print("Kyrie Irving")except KeyError as message:    print(message) #'Kyrie Irving'
Both snippets will run with no problem. For now, it seems okay, we can tolerate writing more lines to deal with the possibility of KeyError. Nevertheless, it will become annoying when the code you are writing is wrong.
Luckily, there are better ways to do it. Not one, but two better ways! Buckle up your seat and get ready!
Using get() Method
Using the get method is one of the best choices you can make when dealing with a dictionary. This method has 2 parameters, the first 1 is required while the second one is optional. However, to use the full potential of the get() method, I suggest you fill both parameters.
First: the name of the key which value you want to retrieve
Second: the value used if the key we are searching does not exist in the
#A dictionary containing basketball players with their heights in mplayersHeight = {"Lebron James": 2.06,                 "Kevin Durant": 2.08,                 "Luka Doncic": 2.01,                 "James Harden": 1.96}#If the key existsprint(playersHeight.get("Lebron James", 0)) #print 2.06print(playersHeight.get("Kevin Durant", 0)) #print 2.08#If the key does not existprint(playersHeight.get("Kyrie Irving", 0)) #print 0print(playersHeight.get("Trae Young", 0)) #print 0
When the key exists, get() method works exactly the same to referencing the name of the key in a square bracket. But, when the key does not exist, using get() method will print the default value we enter as the second argument.
If you don’t specify the second value, a None value will be returned.
You should also note that using the get() method will not modify the original dictionary. We will discuss it further later in this article.
Using setdefault() method
What? There is another way? Yes of course!
You can use setdefault() method when you not only want to skip the try-except step but also overwrite the original dictionary.
#A dictionary containing basketball players with their heights in mplayersHeight = {"Lebron James": 2.06,                 "Kevin Durant": 2.08,                 "Luka Doncic": 2.01,                 "James Harden": 1.96}#If the key existsprint(playersHeight.setdefault("Lebron James", 0)) #print 2.06print(playersHeight.setdefault("Kevin Durant", 0)) #print 2.08#If the key does not existprint(playersHeight.setdefault("Kyrie Irving", 0)) #print 0print(playersHeight.setdefault("Trae Young", 0)) #print 0
What I mean by overwriting is this, when you see the original dictionary again, you will see this.
print(playersHeight)"""print{"Lebron James": 2.06, "Kevin Durant": 2.08, "Luka Doncic": 2.01, "James Harden": 1.96, "Kyrie Irving": 0, "Trae Young": 0}
Other than this feature, the setdefault() method is exactly similar to the get() method.
Both get() and setdefault() are advanced techniques that you all must familiarize with. Implementing it is not hard and straightforward. The only barrier for you now is to break those old habits.
However, I believe that as you use it, you will experience the difference immediately. After a while, you will no longer hesitate to change and start using get() and setdefault() methods.
Remember, when you don’t want to overwrite the original dictionary, go with get() method.
When you want to make changes to the original dictionary, setdefault() will be the better choice for you.