954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read text file as dictionary

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.

eddy80310
Newbie Poster
1 post since Aug 2009
Reputation Points: 10
Solved Threads: 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.

willygstyle
Junior Poster in Training
60 posts since Aug 2009
Reputation Points: 17
Solved Threads: 9
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You