3

I'm sort of new to programming. I have created a class that uses list comprehension in its initializer. It is as follows:

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 alright for a novice. It works! But I don't exactly understand how this would be represented in a for-loop. My guess was terribly wrong:

self.counts =[] 
for word in s_words:
    self.counts = [word, l_words.count(word)]
dict(self.counts)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

3 Answers3

4

This is what your comprehension is as a for loop:

dictlist = []
for word in s_words:
    dictlist.append([word, l_words.count(word)])
self.counts = dict(dictlist)
mhlester
  • 22,781
  • 10
  • 52
  • 75
2

Your guess was not wrong at all; you just forgot to append and assign back to self.counts:

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

That's what a list comprehension does, essentially; build a list from the loop expression.

You could also translate that to a dictionary comprehension instead:

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

or better still, use a collections.Counter() object and save yourself all that work:

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())

The Counter() object goes about counting your words a little more efficiently, and gives you additional helpful functionality such as listing the top N counts and the ability to merge counts.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You are essentially creating a dictionary, where the key of the dictionary is the word and the value corresponding to that key is the number of times the word appears.

self.counts ={}

for word in s_words:
   self.counts[word] = l_words.count(word)
Ashwin Balamohan
  • 3,303
  • 2
  • 25
  • 47