The Right Way to Access Dictionaries in Python

Effectively accessing dictionaries data with Python’s get() and setdefault().



The Right Way to Access Dictionaries in Python
Image by Author

 

When working with data, especially if using our beloved Python language, the dictionary stands out as a fundamental data structure, ready to uncover its data to those who know how to unlock it. 

A dictionary in Python is a collection that is both unordered and mutable, designed to store data values like a map. Unlike other Data Types that hold only single values as elements, Dictionary holds pairs of keys and values separated by colons, a “:” element. 

This Key-value pairs structure provides a way to store data so that it can be efficiently retrieved by key rather than position.

However, most times an unwanted KeyError when looking for a key can break our whole execution. This is why this guide attempts to shed some light and explain some effective ways to access dictionaries avoiding the break of our execution. 

 

Understanding the Python Dictionary

 

Imagine a dictionary as a dynamic storage system, where each item you wish to store has a unique identifier or 'key' that leads you directly to it. 

 

The Right Way to Access Dictionaries in Python
Image by Author

 

In Python, dictionaries are declared with curly brackets {}, with keys and their corresponding values separated by colons “:”, and each pair separated by commas. 

Here's a simple representation:

# Creating a simple dictionary with keys and values
salaries = {
   'Data Scientist': 100000,
   'Data Analyst': 80000,
   'Data Engineer': 120000}

print(salaries)

 

Creating a dictionary is just the beginning. The true utility of dictionaries is realized when retrieving and manipulating this stored data.

 

The Common Pitfall

 

A common approach to accessing a value in a dictionary is by using the key name within square brackets:

# Accessing a value using the key
print(salaries['Data Scientist'])  # Outputs: 100000

print(salaries['Professor'])  # This will raise a KeyError, as 'Professor' key doesn't exist

 

This method seems straightforward until you encounter a key that doesn't exist within the dictionary, leading to a KeyError. 

This is a common issue that can complicate larger projects.

 

The Safer Approaches

 

To avoid KeyError, you might consider using if statements or try-except blocks to handle missing keys. 

These methods, while functional, can become cumbersome with more complex code. Fortunately, Python offers more elegant solutions, mainly two: 

  • the get() method
  • the setdefault() method

 

Embracing the get() Method

 

The get() method is a more efficient way to retrieve values from a dictionary. It requires the key you're searching for and allows an optional second parameter for a default value if the key is not found.

# Using get() to safely access a value
salary = salaries.get('Data Scientist', 'Key not found')
print(salary)  # Outputs: 30

# Using get() with a default value if the key doesn't exist
salary = salaries.get('Professor', 'Key not found')
print(salary)  # Outputs: 30

 

This is the most straightforward way to access a dictionary while ensuring there won’t be a KeyError. Having a default alternative is a safe way to make sure everything is in order. 

However, this method does not alter our dictionary, and sometimes, we require the dictionary to store this new parameter. 

This leads us to the second approach. 

 

Leveraging the setdefault() Method

 

For scenarios where you not only want to retrieve a value safely but also update the dictionary with new keys, setdefault() becomes invaluable. 

This method checks for the existence of a key and if absent, adds the key with the specified default value, effectively modifying the original dictionary.

# Using setdefault() to get a value and set it if not present
salary = salaries.setdefault('Professor', 70000)
print(salary)  # Outputs: 70000 since 'Professor' was not in the dictionary

# Examining the dictionary after using setdefault()
print(salaries) # Outputs: {'Data Scientist': 100000, 'Data Analyst': 80000, 'Data Engineer': 120000, 'Professor': 70000}

 

Examining playersHeight after using setdefault() will show the newly added keys with their default values, altering the original dictionary structure.

 

Final Recommendations

 

The choice between get() and setdefault() depends on your specific needs. Use get() when you simply need to retrieve data without altering the original dictionary. Opt for setdefault() when your task requires adding new entries to the dictionary.

Breaking old habits may require some effort, but the transition to using get() and setdefault() can significantly enhance the robustness and readability of your Python code. 

As you integrate these methods into your programming practice, you'll quickly appreciate their efficiency and the seamless way they handle potential errors, making them indispensable tools in your Python arsenal.

The pivotal role of get() and setdefault() emerge as great ways to handle such formats and access our dictionaries. 

I hope this guide was useful, and next time you are dealing with dictionaries, you can do it in  more effectively. 

You can go check the corresponding Jupyter Notebook in the following GitHub repo.
 
 

Josep Ferrer is an analytics engineer from Barcelona. He graduated in physics engineering and is currently working in the data science field applied to human mobility. He is a part-time content creator focused on data science and technology. Josep writes on all things AI, covering the application of the ongoing explosion in the field.