Understanding List Comprehension

I'm kind of new to programming. I created a class that uses list comprehension in its initializer. It looks like this:

class Collection_of_word_counts():
 '''this class has one instance variable, called counts which stores a 
dictionary where the keys are words and the values are their occurences'''

def __init__(self:'Collection_of_words', file_name: str) -> None:
    '''  this initializer will read in the words from the file,
    and store them in self.counts'''
    l_words = open(file_name).read().split()
    s_words = set(l_words)

    self.counts = dict([ [word, l_words.count(word)] 
                        for word 
                        in s_words])

I think I did well for beginners. It works! But I do not quite understand how this will be presented in the for-loop. My hunch was terribly wrong:

self.counts =[] 
for word in s_words:
    self.counts = [word, l_words.count(word)]
dict(self.counts)
+3
source share
3 answers

Your hunch was not wrong; you just forgot to add and assign back self.counts:

counts = [] 
for word in s_words:
    counts.append([word, l_words.count(word)])
self.counts = dict(counts)

What the list understands is essentially; create a list from a loop expression.

You can also translate this into a dictionary understanding:

self.counts = {word: l_words.count(word) for word in s_words}

or better yet, use collections.Counter()an object and save everything that works:

from collections import Counter

def __init__(self:'Collection_of_words', file_name: str) -> None:
    '''  this initializer will read in the words from the file,
    and store them in self.counts'''
    with open(file_name) as infile:
        self.counts = Counter(infile.read().split())

Counter() , N .

+2

for:

dictlist = []
for word in s_words:
    dictlist.append([word, l_words.count(word)])
self.counts = dict(dictlist)
+4

You essentially create a dictionary where the dictionary key is the word, and the value corresponding to this key is the number of times the word appears.

self.counts ={}

for word in s_words:
   self.counts[word] = l_words.count(word)
0
source

All Articles