简体   繁体   中英

Iterating the lines of a text file and then returning a dictionary in python?

I'm supposed to write a function that will open a data file, where each data file resembles this:

WH239,  Mountain Bike Wheel,            5000

Where the id is WH239, the description is 'Mountain Bike Wheel' and the cost is 5000

The function then assigns the id as a key in a dictionary and the description and price as the value, what I wanted do was create a loop that puts each line into a list with all whitespace stripped and then assign the appropriate index to the key and value of the dictionary, so far I'm stuck on this:

def load_parts(): 
    doc = open('parts.txt', 'U')
    data = doc.read()
    data = data.split('\n')
    for item in data:    
        formatted_line = item.split(',')

I haven't gotten onto stripping the whitespace because when I tell it to return formatted_line in the for loop it only returns the first element of data.

I can only use built in commands in python, any help is appreciated!

Sorry, yeah it is homework, as to be expected I'm not expecting an answer, just a point in the right direction, I can only use functions in the built-in library.

you should try something like

doc = open('your file')
for line in doc.readline():
    if len(line) != 0:
        line.split(',')
code:
    import sys,os
    lis = []
    my_dict = {}

    def load():
        doc = open('/home/sahil/python/file.txt','U')
        data = doc.read()
        data = data.split('\n')
        for item in data:
             formatted_line = item.split(',')
             lis.append(formatted_line)
        return lis  



     def assign(enter_the_list):
         length = len(enter_the_list)-1
         for item in range(length):
             k= enter_the_list[item]
             my_dict[k[0]] = k[1].strip(' ')+' '+k[2].strip(' ')
         print my_dict

     if __name__ == "__main__":
         k = load()
         assign(k)

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