Best way to turn word list into frequency dict
I find that the easiest to understand (while might not be the most efficient) way is to do:
{i:words.count(i) for i in set(words)}
Just a note that, starting with Python 2.7/3.1, this functionality will be built in to the collections
module, see this bug for more information. Here's the example from the release notes:
>>> from collections import Counter
>>> c=Counter()
>>> for letter in 'here is a sample of english text':
... c[letter] += 1
...
>>> c
Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
'p': 1, 'r': 1, 'x': 1})
>>> c['e']
5
>>> c['z']
0
Kind of
from collections import defaultdict
fq= defaultdict( int )
for w in words:
fq[w] += 1
That usually works nicely.