Home > Software engineering >  How to count occurence of a word in a dictionary comprehension
How to count occurence of a word in a dictionary comprehension

Time:11-22

So i am trying to find the occurrences of all the words in a list using dictionary comprehension using the length of the word as the key, and then the occurrence of the length of the word as the value.

def words_lengths_map(text):
    mod_text = ["hello", "this", "is", "a", "list", "of","words"]
    dict1 = {len(k): k.count(k) for k in mod_text}
    print(dict1)

This produces the correct key but my value is always 1. My expected output should be {5:2, 4:2, 2:2, 1:1}

Thank you

CodePudding user response:

You need to count k in mod_text, not in itself (which would always yield 1).

def words_lengths_map(text):
    mod_text = text.split()
    #['this','this','is', 'is', 'a']
    dict1 = {len(k): mod_text.count(k) for k in mod_text}
    print(dict1)
    #{4: 2, 2: 2, 1: 1}

words_lengths_map("this this is is a")

CodePudding user response:

You cannot do this efficiently with a comprehension as you would need a reference to the dict meanwhile is being created. Instead, you could update the counter dict inside a plain loop where you increment the value of the counter if the key is present in the dict, otherwise you set it to one:

counter = {}
for word in mod_text:
    n = len(word)
    if n in counter:
        counter[n]  = 1
    else:
        counter[n] = 1


print(counter)
# {5: 2, 4: 2, 2: 2, 1: 1}

CodePudding user response:

I might misunderstand your question, but you can count each occurence using the Counter class in the collections module here

e.g

from collections import Counter
mod_text = ["hello", "this", "is", "a", "list", "of","words"]
lengths = [len(p) for p in mod_text] #Get the length of each word
c = Counter(lengths) 
print(c)

#Counter({5: 2, 4: 2, 2: 2, 1: 1})
  • Related