Fairly new to Python. I'm working on making a code more eloquent by trying to minimally write a nested for loop within a nested for loop to ultimate create a dictionary, where the dictionary includes the words as key and the frequency of words as values in a file. I believe I figured out how to do the inner for loop using dictionary comprehension but am having trouble figuring out the syntax for the outer for loop. I am guessing the outer for loop would be set up as a list comprehension expression. Currently I am not going to worry about what type of character is being considered a word (symbol, number, alphabet), and am trying to avoid importing any additional libraries. Could you maybe show me some examples, or point me to a resource I could read up more into nested comprehensions/advanced comprehensions?
The "brute force" fundamental method I originally developed looks along the lines of this:
word_cache = {}
# Some code here
with open('myfile.txt') as lines:
for line in lines:
for word in line.split():
word_cache[word]=word_cache.get(word,0)+1
'''
Below is alternatively what I have for dictionary comprehension.
The "for line in lines" is what I am having difficulty trying to nest which I believe would replace the "line in the dictionary comprehension". Part of the issue I see is lines is considered a file object.
'''
word_cache.update({word:word_cache.get(word,0)+1 for word in line.split()})
# Tried the below but did not work because this is the (line for line in lines) is a generator expression
word_cache.update({word:word_cache.get(word,0)+1 for word in (line for line in lines).split()})
Could someone help me understand what is the correct syntax for nested comprehensions of file objects (assuming the object file comes from a txt file)?
Just put the for loops one after another:
See the last example of PEP 274
As mentioned in the comments, a comprehension doesn't really help in your context as the assignment will only occur when the loops are completed.
Comprehensions are sometimes very useful, but they're only syntactic sugar. Nothing that a plain for loop can't do.