0

I have a list of words

words = ['two', 'forks.', 'one', 'knife.', 'two', 'glasses.','one', 
'plate.', 'one', 'naptkin.', 'his,' 'glasses.', 'his', 'knife.']

and need to count the occcurence of words using a dictionary like so.

word_counts = {'two':2, 'one':3, 'forks.':1, 'knife.':2, \
           'glasses.':2, 'plate.':1, 'naptkin.':1, 'his':2}

How would I go about doing this? Thanks for the help!

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64

3 Answers3

4
from collections import Counter
words = ['two', 'forks.', 'one', 'knife.', 'two', 'glasses.','one', 'plate.', 'one', 'naptkin.', 'his,' 'glasses.', 'his', 'knife.']
dict(Counter(words))
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45
0
words = ['two', 'forks.', 'one', 'knife.', 'two', 'glasses.','one',
'plate.', 'one', 'naptkin.', 'his,' 'glasses.', 'his', 'knife.']

d = {}
for w in words:
    if w in d.keys():
        d[w] += 1
    else:
        d[w] = 1

print(d)
logicOnAbstractions
  • 2,178
  • 4
  • 25
  • 37
0

The first solution is similar to that of Francky_V, but make use of the .setdefault() method. For example:

>>> d = {}
>>> d.setdefault('two', 0) # 'two' is not in d, we can set it 
0
>>> d.setdefault('two', 1000)  # 'two' is now in d, we cannot set it, returns current value
0

So, the solution:

d = {}
for word in words:
    d.setdefault(word, 0)
    d[word] += 1

The second solution makes use of collections.defaultdict:

import collections
d = collections.defaultdict(int)
for word in words:
    d[word] += 1

This works because d is a defaultdict with int for values. The first time we mention d[word], the value is automatically set to 0.

Of course, the collections.Counter is the best solution because that class is built for this purpose.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93