Juandev
(Jan Lochman)
1
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)
abessman
(Alexander Bessman)
2
What is fhand
? What should the four dictionaries contain?
Juandev
(Jan Lochman)
3
fhand
is a file containing four lines of text.
What should the four dictionaries contain?
Words from the file and its frequence.
abessman
(Alexander Bessman)
4
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
Juandev
(Jan Lochman)
5
Why list with four dictionaries? I cannot create four separate dictionaries?
abessman
(Alexander Bessman)
6
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
abessman
(Alexander Bessman)
8
Good point. Correction:
piv = [{word: line.split().count(word) for word in line.split()} for line in fhand]
abessman
(Alexander Bessman)
9
A Counter
might be a more appropriate data type:
from collections import Counter
piv = [Counter(line.split()) for line in fhand]
1 Like
Juandev
(Jan Lochman)
10
Ummm and if you run a loop within a list, piv
will not be a list?
abessman
(Alexander Bessman)
11
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