write the values of an ordered dictionary into a file
Peter Otten
__peter__ at web.de
Thu Jun 21 13:49:30 EDT 2018
Ganesh Pal wrote:
> Hi Team
There is no team, just some random guys on the net. Sorry to disappoint
you...
> 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 ||*
Here's one way, written in Python 3.
widths = [len(ch) for ch in header_list]
def print_row(values, widths=widths, file=None):
print(
"||",
"||".join("{:^{}}".format(v, w) for v, w in zip(values, widths)),
"||", sep="", file=file
)
print_row(header_list)
print_row(student.values())
In Python 2 it should work after
from __future__ import print_function
or by replacing print() with a few file.write() calls.
More information about the Python-list
mailing list