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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.