For row in: do not return all rows

I am trying to go through a text file and take each line and put it in a dictionary. Example: If a txt file is used with

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 contains only a partial list. If I use this code (not trying to build a dictionary just by testing):

def word_dict():
fin = open('words2.txt','r')
i = 1
while fin.readline():
    txt = fin.readline().strip()
    print(i,'.',txt)
    i += 1

Same. It prints a list of incomplete values. However, the list matches the dictionary values. What am I missing?

+4
source share
2 answers

You are trying to read lines twice.

Just do the following:

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 of things.

  • , . .
  • () return . .
  • enumerate.

{line.strip(): i for i, line in enumerate(input_file, 1)} - , . :

words = {}
for i, line in enumerate(input_file, 1):
    words[line.strip()] = i
+7

, readline(). :

def word_dict():
    fin = open('words2.txt','r')
    dict_words = dict()
    i = 1
    for line in fin:
        txt = line.strip()
        dict_words.update({txt: i})
        i += 1
    print(dict_words)
0

Source: https://habr.com/ru/post/1606465/


All Articles