Stop Using Square Bracket Notation to Get a Dictionary’s Value in Python
The Traditional (Bad) Way to Access a Dictionary Value

The traditional way to access a value within a dictionary is to use square bracket notation. This syntax nests the name of the term within square brackets, as seen below.

author = {

"first_name": "Jonathan",

"last_name": "Hsu",

"username": "jhsu98"

} print(author['username']) # jhsu98

print(author['middle_initial']) # KeyError: 'middle_initial'

Notice how trying to reference a term that doesn’t exist causes a KeyError . This can cause major headaches, especially when dealing with unpredictable business data.

While we could wrap our statement in a try/except or if statement, this much care for a dictionary term will quickly pile up.

author = {} try:

print(author['username'])

except KeyError as e:

print(e) # 'username' if 'username' in author:

print(author['username'])

If you come from a JavaScript background, you may be tempted to reference a dictionary value with dot notation. This doesn’t work in Python.
['Jonathan Hsu']
['Software Development', 'Programming', 'Data Science', 'Python', 'Technology']