I am trying to traverse a text file and take each line and put it into a dictionary. Ex: If the txt file is a b c
I am trying to create a dictionary like
word_dict = {'a':1, 'b:2', 'c':3}
When I use this code:
def word_dict():
fin = open('words2.txt','r')
dict_words = dict()
i = 1
for line in fin:
txt = fin.readline().strip()
dict_words.update({txt: i})
i += 1
print(dict_words)
My dictionary only contains a partial list. If I use this code (not trying to build the dictionary, just testing):
def word_dict():
fin = open('words2.txt','r')
i = 1
while fin.readline():
txt = fin.readline().strip()
print(i,'.',txt)
i += 1
Same thing. It prints a list of values that is incomplete. The list matches the dictionary values though. What am I missing?
You're trying to read the lines twice.
Just do this:
def word_dict(file_path):
with open(file_path, 'r') as input_file:
words = {line.strip(): i for i, line in enumerate(input_file, 1)}
return words
print(word_dict('words2.txt'))
This fixes a couple things.
return
values instead of printing them. This allows you to use the results of the function in further computation.enumerate
.This line {line.strip(): i for i, line in enumerate(input_file, 1)}
is what's known as a dictionary comprehension. It is equivalent to the follow code:
words = {}
for i, line in enumerate(input_file, 1):
words[line.strip()] = i
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With