0

I have a list of words. I want to create a dictionary in which I have a count of every word in the format <"word" : count(INT)>.

for example:

words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't",
    'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're",
    'under'
]

and the dictionary should be like:

count_dict = {
    "look" : 4,
    "into" : 3,
    "my" : 3,
    "eyes" : 8,
    "the" : 5,
    "not" : 1,
    "around" : 2,
    "don't" : 1,
    "you're" : 1,
    "under" : 1
}

The code that I tried is:

count_d = dict({})

for word in words:
    if len(count_d) == 0:
        count_d.update({word: 1})                   # null dict checking
    else:
        for key in list(count_d.keys()):
            if key == word:                         # if key already present
                initial_value = count_d[key]
                new_value = count_d[key] + 1
                count_d.update({key : new_value})
            else:                                   # if key is not present
                count_d.update({word : 1})

From this code, every key has a 1 value in the dict. Help me with this, I know this is very basic but I am a newbie in this. Thanks in advance.

Mayur Tripathi
  • 69
  • 2
  • 12

1 Answers1

0

Use Counter

>>> from collections import Counter

>>> Counter(words)
Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, "you'r
e": 1, "don't": 1, 'under': 1, 'not': 1})
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37