![]() |
How can this for loop work without : ? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How can this for loop work without : ? (/thread-31456.html) |
How can this for loop work without : ? - Pedroski55 - Dec-13-2020 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_wordThe 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! RE: How can this for loop work without : ? - palladium - Dec-13-2020 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 |