Square Bracket Notation to Get a Dictionary's Value in Python

Square Bracket Notation to Get a Dictionary's Value in Python
Square Bracket Notation to Get a Dictionary's Value in Python

A dictionary is an unordered set of terms and definitions. That means that:

  • Each data point has an identifier (term) and a value (definition).
  • The terms must be unique to that dictionary — no repetitions.
  • The terms have no explicit order — unlike a list.

To define a dictionary, use curly braces and separate each term/definition pair with a comma.

author = {
   "first_name": "Jonathan",
   "last_name": "Hsu",
   "username": "jhsu98"
}

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 author['username']:
   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.

author = {
   "first_name": "Jonathan",
   "last_name": "Hsu",
   "username": "jhsu98"
}
print(author.username)
# AttributeError: 'dict' object has no attribute 'username'

Using the .get() Method

When you want to access a dictionary’s value, the safest way to do so is by using the .get() method. This method has two parameters:

  • First (required): the name of the term to be retrieved. This can be a String or a variable, allowing for dynamic term retrieval.
  • Second (optional): the value to be used as a default if the term doesn’t exist.
author = {
   "first_name": "Jonathan",
   "last_name": "Hsu",
   "username": "jhsu98"
}
print(author.get('username')) # jhsu98
print(author.get('middle_initial'), None) # None

When the term has previously been declared, .get() works no differently than a traditional square bracket reference. In the event that the term isn’t defined, a default value is returned that saves you from having to handle an exception.

This default value can be anything you wish, but remember that it’s optional. When no default value is included, None— the Python equivalent of null — is used.

Using the .setdefault() Method

Sometimes, not only do you want to protect from an undefined term in your dictionary, but you also want your code to self-correct its data structures. The .setdefault() is structured identically to .get(). However, when the term is undefined, in addition to returning a default value, the dictionary’s term will be set to this value as well.

author = {
   "first_name": "Jonathan",
   "last_name": "Hsu",
   "username": "jhsu98"
}
print(author.setdefault('username')) # jhsu98
print(author.setdefault('middle_initial', None)) # None

In the above example, we see that .setdefault() is the exact same as square bracket notation or .get() when the term exists. Additionally, it behaves the same as .get() when the term doesn’t exist, returning the passed default value.

Where it differs from .get() is that the term and definition are now part of the dictionary, as seen below.

author = {
   "first_name": "Jonathan",
   "last_name": "Hsu",
   "username": "jhsu98"
}
print(author.setdefault('middle_initial',None)) # None
print(author)
"""
{
  'first_name': 'Jonathan',
  'last_name': 'Hsu',
  'username': 'jhsu98',
  'middle_initial': None
}
"""

Both .get() and .setdefault() are superior techniques when referencing dictionary values… it just may take some time breaking old habits and adopting the practice.

When you don’t want to alter the original data, .get() is your winner.

When you want to alter the original data, use .setdefault() and call it a day.

Suggest:

Python Tutorials for Beginners - Learn Python Online

Learn Python in 12 Hours | Python Tutorial For Beginners

Complete Python Tutorial for Beginners (2019)

Python Programming Tutorial | Full Python Course for Beginners 2019

Python Tutorial for Beginners [Full Course] 2019

Introduction to Functional Programming in Python