0

I have a text file(computer.txt) with informations about (computer ID) (computer brands), (price) and (computer parts:number required). It looks like the following


comp123, Sam sung, GC323:3,MC202:2,KB132:1
comp423, Acer, GC232:1,SP666:2,WC132:3
comp341, Asus, LP123:3,MM231:3,LA123:3

How can i read this text file and output as a dictionary.

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by willygstyle
0

I would break it down into steps. If I were doing it I might read it in as a list, then parse the elements of the list to create my dictionary.

mlist = []
newfile = open("comp.txt", "rt")
for item in newfile:
     mlist.append(item)
print(mlist)

Then just manipulate the text however you see fit, if every first item starts with comp that gives you a starting point. You could use some temporary lists to seperate they key from the other data. For example.

tmp1 = []
tmp2 = []
for item in mlist:
     if "comp" in item:
          tmp1.append(item[0:6]) '''assuming that the length doesn't change'''
     else:
          tmp2.append(item[9:len(item)])

I'm sure there are simpler ways but this should give you an idea of how to break it down into steps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.