Python Forum

Full Version: How can this for loop work without : ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am working my way through Reuven Lerner's book Python Workout (great book!).

On page 86 is a program to find the longest words.

I have 10 books from gutenberg.org as text files.

I changed the find_longest_word function so it would not return web addresses and other things as long words.

def find_longest_word(filename):
    def fakeWords(word):
        notWanted = ['/', '_', '-', '—', '(', '@', 'www', '—', '"', 'ï', '»']
        for sign in notWanted:
            if sign in word:
                return True
    # first the longest word is empty
    longest_word = ''
    # check each line 1 line at a time
    for one_line in open(filename):
        # check each word for length
        for one_word in one_line.split():            
            if fakeWords(one_word):
                continue
            else:
                word = one_word.replace('"', '').replace(',', '').replace('.', '').replace('”', '')
                if len(word) > len(longest_word):
                    longest_word = word
    return longest_word
The part that puzzles me is this main function (apparently this is called a dictionary comprehension):

# this works great, about 5 seconds for 10 books!
def find_all_longest_words(dirname):    
    return {filename:
            find_longest_word(os.path.join(dirname, filename))
            for filename in os.listdir(dirname)
            if os.path.isfile(os.path.join(dirname, filename))}
Why doesn't the for loop, without : and no indent throw an error??

If I put : after the for loop declaration, then I get an error!
It is called dictionary comprehension. Basically the code is roughly equivalent to:

def find_all_longest_words(dirname):
   dict = {}
   for filename in os.listdir(dirname):
      if os.path.isfile(os.path.join(dirname,filename)):
        dict.update({filename:find_longest_word(os.path.join(dirname,filename})
   return dict