1

Very new to this, appreciate your patience.

I have a txt file of a poem. Ultimately I want create a dictionary such that my key is the line# and the value is the text on that line. For instance, if my poem is this:

Roses are red,

Violets are blue.

I would like my dictionary to be:

dictionary = {1: 'Roses are red', 2: 'Violets are blue'} 

Ultimately I want my program to allow me to search for a line of the poem by entering the line number (the key).

I've started off by doing this--

def getFile():
    prose = str(input('Please enter the file path for your text file: '))

    dictionary = {}

    infile = open(prose, 'r')
    for line in infile:
        dictionary[line] += 1
        print(dictionary)
    infile.close()

getFile()

But I'm lost and don't know what to do next. I've tried looking this up, I'm not understanding this. Any help would be much appreciated.

4 Answers 4

3

Your issue is here:

for line in infile:  # iterate over each line of text
    dictionary[line] += 1  # this tries to use the text as a dict key instead of value
    print(dictionary)  # I assume this is just here to display the current state of the dictionary eacy loop

You need a way to track which line you are on. Thankfully, enumerate() can help:

for line_number, line in enumerate(infile):
    dictionary[line_number] = line
    print(dictionary)
Sign up to request clarification or add additional context in comments.

1 Comment

And you can use enumerate(infile, 1) to start counting from one as the OP appears to want to do... or just do it in one go: dictionary = dict(enumerate(infile, 1))
1

You can define a new variable line_num that keeps track of line numbers

def getFile():
    prose = str(input('Please enter the file path for your text file: '))

    dictionary = {}

    infile = open(prose, 'r')
    line_num = 1
    for line in infile:
        dictionary[line_num] = line
        line_num += 1
    print(dictionary)
    infile.close()

getFile()

You can view the dictionary with line numbers as keys and each line as their values

Output:

{1: 'roses are red\n', 2: 'violets are blue'}

4 Comments

Manually maintaining an index while iterating is usually the wrong (and slow, and verbose) approach. Just use enumerate: for line_num, line in enumerate(infile): (add a second argument of 1 [or start=1] to the enumerate call to start from 1 instead of 0).
This works! Thank you!!! I've spent hours on this. I really appreciate your help.
@ShadowRanger Did not know that. Thank you. Noted!
@yklsga Just did. Thanks again.
1
dictionary = {}
f = open(myfile, 'rb')
for index, line in enumerate(f.readlines()):
   dictionary[index] = line
f.close()

There are several issues with your code - first

for line in infile:
    dictionary[line] += 1

Line here will be the dictionary key, but you want it to be the value:

dictionary[index] = line

You also are not presently tracking the index - either use enumerate as above, or create a variable and increment it every time through the loop. Your present code will I believe just throw an error, as you're trying to increment dictionary[line] which does not yet exist.

1 Comment

Drop the .readlines() part; files are already iterables of their lines, so all this does is force the whole file to be slurped before you can begin processing (and in other cases, where you're not storing the whole file, just processing lines and throwing them away, it means storing the whole file in memory even when you only need a line at a time). enumerate(f) would work fine, and get going faster (it might even give the OS time to prefetch the next part of the file as you're doing the work for the current lines, though that's not the reason you're doing it).
0

I'll do a little different

def getFile(infile):
    prose = str(input('Please enter the file path for your text file: '))

    dictionary = {}

    infilelines = list(open(prose, 'r'))
    for line in enumerate(infilelines):
        dictionary[line[0]] = line[1]
    infile.close()
    return dictionary

print(getfile('someInput.txt'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.