Analytics Tips #3 - The Right Way to Access Dictionaries in Python
Effectively accessing dictionaries data with .get() and .setdefault().
Hey everyone! This is Josep, one more week 👋🏻
This week, we have a third issue of the Analytics Tips series, where we'll explore different aspects of data science in an easy-to-understand way.
When working with Python, 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.
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.
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:
salaries = {
'Data Scientist': 100000,
'Data Analyst': 80000,
'Data Engineer': 120000
}
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
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
1. 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: 100000
# Using get() with a default value if the key doesn't exist
salary = salaries.get('Professor', 'Key not found')
print(salary) # Outputs: Key not found
2. 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' is not found.
# Examining the dictionary after using setdefault()
print(salaries) # Outputs:
{
'Data Scientist': 100000,
'Data Analyst': 80000,
'Data Engineer': 120000,
'Professor': 70000
}
Examining the salaries dictionary 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.
To learn more you can check the following article.
And this is all for now!
If you have any suggestions or preferences, please comment below or message me through my social media!
Remember you can also find me in X, Threads, Medium and LinkedIn 🤓
Loved the content man really appreciate your writing style and the code parts were cherry on top.