Home > Enterprise >  Missing keys from dictionary counting words in list
Missing keys from dictionary counting words in list

Time:01-01

My output is incomplete. There are 3 element which don't count.

# A programm to count words in a string and put them in a dictionary as key = word and value = count

def word_in_str (S):
    dict_s = {}   # make a empty dict

    s = S.lower() # make string lowercase
    l = s.split() # split string into a list and separate theme by spase

    print (l)     # original list contain all words

    for word in l:
        counter = l.count (str(word)) 

        print (str(word))  # for testing the code, it's value = count
        print (counter)    # for testing the code, it's key = word

        dict_s[str(word)] = counter 

        l[:] = (value for value in l if value != str(word)) #delete the word after count it

        print (l)          # for testing the code, it's the list after deleting the word        

    print (dict_s)         # main print code, but there is no ('when', 'young', 'and') in result


if __name__ == '__main__':    
    word_in_str ('I am tall when I am young and I am short when I am old')

the output for this code is:

['i', 'am', 'tall', 'when', 'i', 'am', 'young', 'and', 'i', 'am', 'short', 'when', 'i', 'am', 'old']
i
4
['am', 'tall', 'when', 'am', 'young', 'and', 'am', 'short', 'when', 'am', 'old']
tall
1
['am', 'when', 'am', 'young', 'and', 'am', 'short', 'when', 'am', 'old']
am
4
['when', 'young', 'and', 'short', 'when', 'old']
short
1
['when', 'young', 'and', 'when', 'old']
old
1
['when', 'young', 'and', 'when'] <==what happened to this words?
{'i': 4, 'tall': 1, 'am': 4, 'short': 1, 'old': 1}  <==result without the words above

CodePudding user response:

I think you're over thinking the problem. A Counter already counts elements of an iterable, and it is a type of dict

from collections import Counter

def word_in_str(S):
    return dict(Counter(S.split()))

The problem with your code is that your for loop is over l, but then you're attempting to "delete" and reassign l[:], where you don't really need to. Just count and store the dict entry.

CodePudding user response:

def word_in_str (S):
    dict_s = {}
    s = S.lower()
    l = s.split()
    for word in l:
        counter = l.count (word)
        dict_s[word] = counter 
    print (dict_s)
    
word_in_str ('I am tall when I am young and I am short when I am old')
  • Related