I was trying to use a dictionary to count word frequency on a given string. Say:
s = 'I ate an apple a big apple'
I understand the best way to count word frequency is probably to use collections.Counter
. But I want to know if I can solve this by using a dictionary comprehension.
My original method(without dictionary comprehension) was
dict = {}
for token in s.split(" "):
dict[token] = dict.get(token, 0) + 1
and it works fine:
dict
{'I': 1, 'a': 1, 'an': 1, 'apple': 2, 'ate': 1, 'big': 1}
I tried to use a dictionary comprehension to this, like
dict = {}
dict = {token: dict.get(token, 0) + 1 for token in s.split(" ")}
But this didn't work.
dict
{'I': 1, 'a': 1, 'an': 1, 'apple': 1, 'ate': 1, 'big': 1}
What's wrong with the dictionary comprehension? Is it because I used itself inside the comprehension so every time I called dict.get('apple', 0
) in the comprehension, I will get 0
? However, I don't know how to test this so I am not 100% sure.
P.S. If it makes any difference, I am using python 3.