The overlooked "get" method of dictionaries

Python dicts have a get method. How could it help us?

We have all learnt how to retrieve a key from a dict. We use the [] indexing operator to look up the value.

a = {"name": "Siddharta", "country": "India"}
print(a["name"])

But did you know that there is another way to get data from a dictionary? Yes, dicts have a get method that can be used to also retrieve the value of a key. Check it out

a = {"name": "Siddharta", "country": "India"}
print(a.get("name"))

Both return the same output. So why does the dict have this get method?

Well, it turns out that get has a superpower that the regular indexing does not. It takes in a second parameter where you can specify a default value. If the key is not present in the dictionary, then the method will return this default value. (If no default value is specified it will return None)

a = {"name": "Siddharta", "country": "India"}
print(a.get("name", "Unknown")) # prints Siddharta
print(a.get("city", "Unknown")) # prints Unknown

In the example above, the dict has a name key, so the first line will return the corresponding value Siddharta which will be printed out. The dict does not have a city key, so it will return parameter 2 which contains the default value. Since we set the default value to Unknown that will be returned in this case. Note that get does not give an error when the key is missing, unlike [].

Back to the word count problem

How do we apply this bit of knowledge to the word count problem?

Recall what we need to do

You want to loop through the words and keep track of the count in a dictionary–if the word is already present in the dictionary then increment its count, otherwise add it to the dictionary with a count of one.

You can do that with a single line of code using get

counts[word] = counts.get(word, 0) + 1

If the word exists in the dictionary, then it will retrieve the current count and increment it. If the word is not in the dictionary, it will return zero (the default value specified), then add one and add it to the dictionary.

This is what the full code would look like

def count_words(line):
    words = line.split()
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts

Isn't that beautiful?

But there is a way to make it even more beautiful. That's in the next article.

Comments

Sign in or become a Playful Python member to join the conversation.
Just enter your email below to get a log in link.