Search code examples
python-3.xcollectionscountcounter

Counting: How do I add a zero if a word does not occur in a list?


I would like to find keywords from a list, but return a zero if the word does not exist (in this case: part). In this example, collabor occurs 4 times and part 0 times.

My current output is

[['collabor', 4]]

But what I would like to have is

[['collabor', 4], ['part', 0]]

str1 = ["collabor", "part"]
x10 = []
for y in wordlist:
    for string in str1:
        if y.find(string) != -1:
            x10.append(y)

from collections import Counter
x11 = Counter(x10) 
your_list = [list(i) for i in x11.items()]
rowssorted = sorted(your_list, key=lambda x: x[0])
print(rowssorted)

Solution

  • Although you have not clearly written your problem and requirements,I think I understood the task.

    I assume that you have a set of words that may or may not occur in a given list and you want to print the count of those words based on the occurrence in the given list.

    Code:

    constants=["part","collabor"]
    wordlist = ["collabor", "collabor"]
    d={}
    for const in constants:
        d[const]=0
    for word in wordlist:
        if word in d:
            d[word]+=1
        else:
            d[word]=0
    
    from collections import Counter
    x11 = Counter(d) 
    your_list = [list(i) for i in x11.items()]
    rowssorted = sorted(your_list, key=lambda x: x[0])
    print(rowssorted)
    

    output:

    [['collabor', 2], ['part', 0]]
    

    This approach gives the required output.

    In python, to get the count of occurrence dictionary is popular.

    Hope it helps!