python dictionary

Stop Using Square Brackets to Get a python Dictionary Values

A python dictionary is an unordered set of keys and values.

That means :

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

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

Example

author = {
   "first_name": "Christos",
   "last_name": "Ploutarchou",
   "username": "christos_ploutarchou"
}

The traditional way to get a Dictionary Value

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

author = {
   "first_name": "Christos",
   "last_name": "Ploutarchou",
   "username": "christos_ploutarchou"
}
print(author['username']) 
#output : christos_ploutarchou 
print(author['surname']) 
#output : KeyError: 'surname'

Notice how trying to reference a term that doesn’t exist causes a KeyError.

These causes cause significant 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 heap up.

Example

author = {}
try:
   print(author['username'])
except KeyError as e:
   print(e) # 'username'
if 'username' in author:
   print(author['username'])

If you come from another programming language like JavaScript, you may be tempted to reference a dictionary value using dot notation. That doesn’t work in Python.

author = {
   "first_name": "Christos",
   "last_name": "Ploutarchou",
   "username": "christos_ploutarchou"
}
print(author.username)
# AttributeError: 'dict' object has no attribute 'username'

Start 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.

Example

author = {
   "first_name": "Christos",
   "last_name": "Ploutarchou",
   "username": "christos_ploutarchou"
}
print(author.get('username')) 
#output : christos_ploutarchou 
print(author.get('middle_initial', None)) 
#output : None

When the term has previously been declared, .get() works no differently than a traditional square bracket reference. If the key isn’t defined, a default value is returned that saves you from handling an exception.
This default value can be anything you want, but remember that it’s optional. When no default value is set, the get() method returns None if the key does not exists.

Start using the .setdefault() Method

Sometimes, not only do you want to protect from an undefined key 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 key is undefined and returning a default value, it will set the dictionary’s key the default value.

Example

author = {
   "first_name": "Christos",
   "last_name": "Ploutarchou",
   "username": "christos_ploutarchou"
}
print(author.setdefault('username')) 
#output : christos_ploutarchou 
print(author.setdefault('middle_initial', None))
#output : None

In the above example, we see that .setdefault() is the same as square bracket notation or .get() when the key exists.

Additionally, it behaves the same as .get() when the term doesn’t exist, returning the passed default value.
It differs from .get() because the term and definition are now part of the dictionary, as we see below.

author = {
   "first_name": "Christos",
   "last_name": "Ploutarchou",
   "username": "christos_ploutarchou"
}
print(author.setdefault('surname',None)) 
#output : None
print(author)
# output
{
   "first_name": "Christos",
   "last_name": "Ploutarchou",
   "username": "christos_ploutarchou",
   "surname": None

}
"""
Both .get() and .setdefault() are superior techniques when referencing dictionary values. 
When you don’t want to alter the original data, .get() is your choise.
When you want to alter the original data, then just use .setdefault() .

Leave a Comment