Search code examples
pythonpython-3.xpython-3.9

(PY4E: Exercise. 9.1) Can anyone please explain how (and why) Line 12 in this code works?


I have been working on the Python for Everybody Chapter 9 Exercise 1.

The exercise assignment is as follows:

Exercise 1: Download a copy of the file www.py4e.com/code3/words.txt

Write a program that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.

And here is link to a screenshot of my code:

Ex 9.1 Screenshot

Basically, I would like an explanation of what Lines 10-12 is actually doing in this code, especially Line 12. (I became stuck/confused with the exercise and took lines 10-12 from another person's example)

I know that the code succeeds in storing all of the words from the file into a dictionary as the exercise asked, but I just don't understand how it did so?

Thank you for your help.


Solution

  • Line 10 loops over all of the words in the list words. The code in lines 11 and 12 is executed for every element in that list, each time keeping the current element in the variable word.

    Line 11 just increments a counter (count) by 1 every loop, I assume just to have something to put as the values in the dictionary.

    Line 12 adds the current value of count to the dictionary make_dictionary at key word.

    The result is a dictionary where the keys are the words from the file, and the values integers starting from 1.