Four dictionaries instead of one

The following code comes up with one dictionary. How can I modify it to get four dictionaries? Not necessary to print them out.

piv = dict()
for line in fhand:
    words = line.split()
    for word in words:
        if word not in piv:
            piv[word] = 1
        else:
            piv[word] += 1

print(piv)

What is fhand? What should the four dictionaries contain?

fhand is a file containing four lines of text.

What should the four dictionaries contain?

Words from the file and its frequence.

One dictionary per line then?

piv = [{word: line.count(word) for word in line.split()} for line in fhand]

piv is now a list containing four dictionaries, with each dictionary holding a per-line word count.

1 Like

Why list with four dictionaries? I cannot create four separate dictionaries?

Sure:

piv0, piv1, piv2, piv3 = [{word: line.count(word) for word in line.split()} for line in fhand]

Caution: This will break if fhand does not contain exactly four lines.

1 Like

If line contains 'the other one' this dict comprehension would return {'the': 3, 'other': 1, 'theme': 1}, incorrectly counting three 'the'.

1 Like

Good point. Correction:

piv = [{word: line.split().count(word) for word in line.split()} for line in fhand]

A Counter might be a more appropriate data type:

from collections import Counter
piv = [Counter(line.split()) for line in fhand]
1 Like

Ummm and if you run a loop within a list, piv will not be a list?

I don’t understand your question. If you want separate dicts (or Counters, in this case) instead of a list, do this:

instead of piv = ...

1 Like