Dictionary is one of the data structures that are ready to use when programming in Python.

Before We Start, What is a Dictionary?

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 m
playersHeight = {"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 Wrong Way

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.06
print(playersHeight["Kevin Durant"]) #print 2.08
print(playersHeight["Luka Doncic"]) #print 2.01
print(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.

#software-engineering #data-science #programming #python #technology

The Right Way to Access a Dictionary
1.25 GEEK