write the values of an ordered dictionary into a file

Ganesh Pal ganesh1pal at gmail.com
Thu Jun 21 13:11:48 EDT 2018


Hi Team



I need to write the values of an ordered dictionary into a file . All
values should be in a single row with a header list



*Example:*



*student = [("NAME", "John"),*

*           ("AGE", 28),*

*           ("SCORE", 13),*

*           ("YEAR", 2018),*

*           ("FEE", 250)]*

*student = OrderedDict(student)*



*The OrderedDict Should be append at the end of the file as as shown below.*


*# tail -2  /tmp/student_record.txt *

*.................................................................*

*||STUDENT NAME||STUDENT AGE||MARKS SCORED||PASSED YEAR||FEES PAID||*

*||John        ||  28       ||  13        || 2018      || 250     ||*





Questions:


(1) Below is my partial solution , any comments and suggestions ( I am not
to get the “||” delimiter correctly, trying it )



#!/usr/bin/python



# A Python program to write the values of an OderedDict into a file

# The values should be formatted correctly under its headers



from collections import OrderedDict

tmp = '/tmp/student_record.txt'



student = [("NAME", "John"),

           ("AGE", 28),

           ("SCORE", 13),

           ("YEAR", 2018),

           ("FEE", 250)]

student = OrderedDict(student)



header_list = ["STUDENT NAME", "STUDENT AGE", "MARKS SCORED", "PASSED YEAR",

                "FEES PAID"]

header_string = '||' + '||'.join(header_list) + '||'



with open(tmp, 'a') as fd:

     for item in header_string:

         fd.write("%s" % (item))



     for value in student.values():

         fd.write("\n")

         fd.write("||")

         fd.write("%s" % (value))





*output:*



*root at X1:/Play_ground/SPECIAL_TYPES# cat /tmp/student_record.txt*

*||STUDENT NAME||STUDENT AGE||MARKS SCORED||PASSED YEAR||FEES PAID||*

*||John*

*||28*

*||13*

*||2018*





(2)Any alternative way to solve this easily and store the data  in the
requested format (can I still use cvs writer to format this)





I am a Linux user with Python 2.7



Regards,
Ganesh



More information about the Python-list mailing list