Wednesday, April 1, 2009

Converting to and from dictionary!!

In this post I will be showing you how to convert a set of data in to dictionary format in python. This was very handy for me while developiing few applications.

While creating ISE RANKLIST I was giving the 5 line code which I mentioned in my vtu post in a for loop. After fetching the result into a local file, to display the same for a particular usn was kind of tough for me. So, I thought of dictionary datastructure in pyhon.

Here is the code to fetch the results in to a file from the terminal.
$ python test.py > test
And here is the code in test.py file

import urllib
for i in range(1,9):
res = urllib.urlencode({'rid' : '1bm06is40'+str(i),'submit':'submit'})
req = urllib.urlopen('http://results.vtu.ac.in/default.php',res)
data = req.readlines()
print data[245]

/* The above code fetches 9 students result. And it will be put into a file test. */

The test file looks like this .

CHANNABASAVA (1bm06is401) Semester:6      Result:  FAIL SubjectExternal InternalTotalResultSoftware Engineering (CS62)452166PManagement Information Systems (IS63)661985PSystem Programming Lab (ISL68)02323ATotal Marks: 174  

HARSHAVARDHANA G (1bm06is403) Semester:7      Result:  FIRST CLASS SubjectExternal InternalTotalResultEngineering and Technology Management (CS71)532376PObject Oriented Analysis and Design (CS72)411960PDistributed Operating System (CS753)472370PJava and CGI Programming (CS73)672491PComputer Networks - II (CS74)542478PClient Server Computing (CS764)552176PNetworks Laboratory (CSL77)452570PCGI Programming Laboratory (CSL78)461965PTotal Marks: 586  

Now to convert it into a dictionary format. Type this at terminal
$python dict.py > test2
This is the code of dict.py

f = file('test')
z={}
while(True):
c=f.readline()
if(c):
d = c.split('')
c = c + f.readline()
try:

name = d[0].split('')[1].split('<')[0]

usn=name.split()[-1][1:-1]

z.update({usn : c })
except:
pass
else :
break

print z

test3 file looks like this below.

{'1rv05is048': 'SHARMA R S (1rv05is048) Semester:7      Result:  FIRST CLASS WITH DISTINCTION SubjectExternal InternalTotalResultEngineering and Technology Management (CS71)731891PPrinciples of User Interface Design (IS761)662187PObject Oriented Analysis and Design (CS72)692493PJava and CGI Programming (CS73)701585PDistributed Operating System (CS753)572279PComputer Networks - II (CS74)542276PNetworks Laboratory (CSL77)442569PCGI Programming Laboratory (CSL78)482472PTotal Marks: 652     \r\n\n'}

/* here the key is USN. Value is Result */

No comments:

Post a Comment