write the values of an ordered dictionary into a file

Peter Pearson pkpearson at nowhere.invalid
Thu Jun 21 13:33:09 EDT 2018


On Thu, 21 Jun 2018 22:41:48 +0530, Ganesh Pal <ganesh1pal at gmail.com> wrote:
[snip]
[what I think OP wants:]
>
> *.................................................................*
>
> *||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*
[snip]

You don't say which aspects of this output you find unsatisfactory and
want help with, but . . .

 - You're writing "\n" in front of every *field*, when you only want to
   write it in front of every line; and

 - To make the columns line up right, you'll want to specify the widths
   of the character strings being written, e.g., using "%10s" in place
   of "%s".

-- 
To email me, substitute nowhere->runbox, invalid->com.



More information about the Python-list mailing list