简体   繁体   中英

Trying to figure out the correct loop for processing multiple lines into a dictionary

grocery_stock.txt contains

lemonade 6 1.1

bread 34 1.43

chips 47 3.76

banans 16 0.79

pizza 15 5.0

This is the code i have written for it so far.

    infile=open("grocery_stock.txt", 'r+')
    lines=infile.readlines()
    line=infile.readline()
    none= ' '
    count = 0
    index= 0
    while line !=none:
        line1=infile.readline()

        while line1 in lines:

            line1=line1.split()
            name1=str(line1[:0])
            quant1=(str(line1[:1]))
            price1=[(str(line1[:2]))]
            grocerystock[name1[0]]=(quant1,name1)

            print (grocerystock)

        line2=infile.readline()
        for line2 in line:
            line1=line2.split()
            name1=str(line1[0])
            quant1=(str(line1[1]))
            price1=[(str(line1[2]))]
            grocerystock[name1[1]]=(quant1,name1)
            print (line1[1], line[2],line1[0])
            print (grocerystock)

        line3=infile.readline()
        line4=infile.readline()
        line5=infile.readline()
    infile.close()

    grocerystock={} 

The reason I am doing this is because later in my project im going to have to remove some keys and change some values so i want a function that i can call anywhere into my program when I read a file to convert the data into a dictionary.

My loops might look crazy to you but I was at the point where I was just trying anything that popped in my head.

Also as you can see i havent finished going through line5, I thought it would be better to figure out the correct loop rather than type random loops and see what happens.

Thank you in advance.

Perhaps this would help:

with file('grocery_stock.txt') as f:
    lines = f.readlines()

# filter out empty lines
lines = [line for line in lines if line.strip() != '']

# split all lines
lines = [line.split() for line in lines]

# convert to a dictionary
grocerystock = dict((a, (b, c)) for a, b, c in lines)

# print
for k, v in grocerystock.items():
    print k, v

The only loop you need is the loop to move the data in line-by-line. That can be accomplished with this:

with open("grocery_stock.txt", "r+") as f:
    for line in f: # Changed to be a more elegant solution; no need to use while here.
        # Here we would split (hint) the line of text.
        dict[split_text[0]] = [split_text[1], split_text[2]]

Since it's homework, I encourage you to look into this solution as well as others. I can't just give you the answer, now can I?

Just some hints, since this is HW:

  • try to use a context manager to open files, that is a with statement ,
  • even if the while is not wrong, I'd prefer a for loop in this case (the number of iterations is fixed - the number of lines) – I sometimes think of while loops as the gateway to the halting problem ...
  • try use readlines() , since the number of lines is probably small; or use something like this (which looks just natural):

     for line in f: # do something with line 

When you use open() and you get a file object, you can just iterate on the file object. Like so:

for line in f:
    # do something with the line

I recommend the above rather than calling f.readline() in a loop.

f.readlines() will read the entire file into memory, and build a list of input lines. For very large files, this can cause performance problems. For a small file such as you are using here, it will work, but if you learn the standard Python idiom you can use it for small files or for large ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM