python – print a list of dictionaries in table form

python – print a list of dictionaries in table form

you can use module tabulate.
The following code is compatible with python 2, for python 3 see in the comments.

>>> import tabulate
>>> dataset =[{Major: Biology, GPA: 2.4, Name: Edward}, {Major: Physics, GPA: 2.9, Name: Emily}, {Major: Mathematics, GPA: 3.5, Name: Sarah}]
>>> header = dataset[0].keys()
>>> rows =  [x.values() for x in dataset]
>>> print tabulate.tabulate(rows, header)
Major          GPA  Name
-----------  -----  ------
Biology        2.4  Edward
Physics        2.9  Emily
Mathematics    3.5  Sarah

you can use tablefmt parameter for different table format

>>> print tabulate.tabulate(rows, header, tablefmt=grid)
+-------------+-------+--------+
| Major       |   GPA | Name   |
+=============+=======+========+
| Biology     |   2.4 | Edward |
+-------------+-------+--------+
| Physics     |   2.9 | Emily  |
+-------------+-------+--------+
| Mathematics |   3.5 | Sarah  |
+-------------+-------+--------+
>>> print tabulate.tabulate(rows, header, tablefmt=rst)
===========  =====  ======
Major          GPA  Name
===========  =====  ======
Biology        2.4  Edward
Physics        2.9  Emily
Mathematics    3.5  Sarah
===========  =====  ======
for dicts in dataset:
    print(dicts.get(Name)),
    print(dicts.get(Major)),
    print(dicts.get(GPA)),

Example

>>> dataset =[{Major: Biology, GPA: 2.4, Name: Edward}, {Major: Physics, GPA: 2.9, Name: Emily}, {Major: Mathematics, GPA: 3.5, Name: Sarah}]
>>> 
>>> for dicts in dataset:
...         print(dicts.get(Name)),
...         print(dicts.get(Major)),
...         print(dicts.get(GPA)),
... 
Edward Biology 2.4 Emily Physics 2.9 Sarah Mathematics 3.5

python – print a list of dictionaries in table form

How about this:

from __future__ import print_function

dataset =[{Major: Biology, GPA: 2.4, Name: Edward},Physics, GPA: 2.9, Name: Emily},Mathematics, GPA: 3.5, Name: Sarah}]

[print(%s %s: %sn%(item[Name],item[Major],item[GPA])) for item in dataset]

result:

Edward Biology: 2.4

Emily Physics: 2.9

Sarah Mathematics: 3.5

Leave a Reply

Your email address will not be published.