Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For line in : not returning all lines

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?

like image 951
Noob123 Avatar asked Mar 14 '23 20:03

Noob123


1 Answers

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.

  1. Functions should not have hard coded variables, rather you should use an argument. This way you can reuse the function.
  2. Functions should (generally) return values instead of printing them. This allows you to use the results of the function in further computation.
  3. You were using a manual index variable instead of using the builtin 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
like image 142
Morgan Thrapp Avatar answered Mar 23 '23 12:03

Morgan Thrapp