Image by author
When working with data, especially using our beloved Python language, the dictionary stands out as a fundamental data structure, ready to reveal your data to those who know how to unlock it.
A dictionary in Python is an unordered, mutable collection, designed to store data values like a map. Unlike other data types that contain only single values as elements, Dictionary contains key-value pairs separated by a colon, a “:” element.
This key-value pair structure provides a way to store data so that it can be efficiently retrieved by key rather than by position.
However, most of the time an unwanted KeyError while searching for a key can interrupt our entire execution. That is why this guide tries to shed some light and explain some effective ways to access dictionaries without interrupting our execution.
Imagine a dictionary as a dynamic storage system, where each item you want to store has a unique identifier or “key” that takes you directly to it.
Image by author
In Python, dictionaries are declared within curly braces {}, with the keys and their corresponding values separated by a colon “:”, and each pair separated by commas.
Here is 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 usefulness of dictionaries comes from retrieving and manipulating this stored data.
A common method of accessing a value in a dictionary is to use the key name enclosed in 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 simple until it encounters a key that does not exist in the dictionary, which raises a KeyError.
This is a common problem that can complicate larger projects.
To avoid KeyError, you might consider using if statements or try-except blocks to handle missing keys.
These methods, while functional, can be cumbersome with more complex code. Fortunately, Python offers more elegant solutions, mainly two:
- the get() method
- the setdefault() method
Adopting the get() method
The get() method is a more efficient way to retrieve values from a dictionary. Requires the key you are looking 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 simplest way to access a dictionary while ensuring that there will not be a KeyError. Having a default fallback is a sure 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 brings us to the second approach.
Taking advantage of the setdefault() method
For scenarios where you not only want to safely retrieve a value 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 playerHeight after using setdefault() will display the newly added keys with their default values, altering the original dictionary structure.
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 take some effort, but transitioning to using get() and setdefault() can significantly improve 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 fundamental role of get() and setdefault() emerges as excellent ways to handle such formats and access our dictionaries.
I hope this guide has been useful and that the next time you work with dictionaries you can do so more efficiently.
You can consult the corresponding Jupyter Notebook in the following GitHub repository.
Joseph Ferrer He is an analytical engineer from Barcelona. He graduated in physical engineering and currently works in the field of Data Science applied to human mobility. He is a part-time content creator focused on data science and technology. You can contact him at LinkedIn, Twitter either Half.