1

Say I have a list of words called words i.e. words = ["hello", "test", "string", "people", "hello", "hello"] and I want to create a dictionary in order to get word frequency.

Let's say the dictionary is called 'counts'

counts = {}
for w in words:
    counts[w] = counts.get(w,0) + 1

The only part of this I don't really understand is the counts.get(w.0). The book says, normally you would use counts[w] = counts[w] + 1 but the first time you encounter a new word, it won't be in counts and so it would return a runtime error. That all fine and dandy but what exactly does counts.get(w,0) do? Specifically, what's the (w,0) notation all about?

4 Answers 4

7

If you have a dictionary, get() is a method where w is a variable holding the word you're looking up and 0 is the default value. If w is not present in the dictionary, get returns 0.

Sign up to request clarification or add additional context in comments.

Comments

6

FWIW, with Python 2.7 and above you may prefer to operate with collections.Counter, like:

In []: from collections import Counter
In []: c= Counter(["hello", "test", "string", "people", "hello", "hello"])
In []: c
Out[]: Counter({'hello': 3, 'test': 1, 'people': 1, 'string': 1})

Comments

4

The dictionary get() method allows for a default as the second argument, if the key doesn't exist. So counts.get(w,0) gives you 0 if w doesn't exist in counts.

1 Comment

It's worth mentioning that if there is no key w in counts, then counts.get(w) will evaluate to None. And the line counts.get(w) + 1 will be equivalent to None + 1, and will throw a TypeError.
0

The get method on a dictionary returns the value stored in a key, or optionally, a default value, specified by the optional second parameter. In your case, you tell it "Retrieve 0 for the prior count if this key isn't already in the dictionary, then add one to that value and place it in the dictionary."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.