We begin in a library, where we want to count book copies. With a small collection, we might be able to tally each one manually. However, as the collection grows, this approach becomes cumbersome and inefficient. A more efficient method uses a HashMap, or a dictionary in Python.
For a quick illustration, consider this list of colors:
If we count manually, red appears twice, blue appears thrice, and green appears once. We can employ HashMaps for a more efficient counting process.
Simple yet powerful, HashMaps allow us to store and retrieve data using keys. The unique colors in our list act as keys, and the count of each color becomes its corresponding value. Let's demonstrate how we can count elements in our colors list using a Python dictionary:
When the above code executes, it displays the counts for each color: {'red': 2, 'blue': 3, 'green': 1}.
Here's how we created a dictionary to count our elements:
We began with an empty dictionary. Then, we went through our list, and for every occurring element, we checked if it was in our dictionary. If it was, we increased its value. If it was not, we added it to the dictionary with a value of 1.
Consequently, this code efficiently counts the colors in our list, showcasing how performant counting can be, even as the list size increases!
Python dictionaries have a get(key, default) method, which is an alternative to checking whether a key already exists in a dictionary. It allows us to fetch the value of a key if it exists, or return a default value specified by you if it doesn't.
The code above can be also written like this:
