'How can I convert a list of words into a dictionary?

I have a txt file of hundreds of thousands of words. I need to get into some format (I think dictionary is the right thing?) where I can put into my script something along the lines of;

for i in word_list:
word_length = len(i)
print("Length of " + i + word_length, file=open("LengthOutput.txt", "a"))

Currently, the txt file of words is separated by each word being on a new line, if that helps. I've tried importing it to my python script with

From x import y

.... and similar, but it seems like it needs to be in some format to actually get imported? I've been looking around stackoverflow for a wile now and nothing seems to really cover this specifically but apologies if this is super-beginner stuff that I'm just really not understanding.



Solution 1:[1]

What you are trying to do is to read a file. An import statement is used when you want to, loosely speaking, use python code from another file.

The docs have a good introduction on reading and writing files -

To read a file, you first open the file, load the contents to memory and finally close the file.

f = open('my_wordfile.txt', 'r')
for line in f:
    print(len(line))
f.close()

A better way is to use the with statement and you can find more about that in the docs as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mortz