0

I would like the output to be table. Without the curly brackets and double quotes. Can I get some help with this? I'm using python 3.7.5

students = [ 
  { "grade": 5,
    "firstname": "Brendon", 
    "lastname": "Urie", 
    "gender": "M" 
    },
  { 
    "grade": 7,
    "firstname": "Freddy",
    "lastname": "Mercury",
    "gender": "M" 
  },
  { 
    "grade": 12,
    "firstname": "Tessa",
    "lastname": "Thompson"
  }
]

output("list", students, None)
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76

3 Answers3

1

You can use the pandas to print it as dataframe.

import pandas as pd

students = [ 
    { 
        "grade":5,
        "firstname":"Brendon",
        "lastname":"Urie",
        "gender":"M"
    },
    { 
        "grade":7,
        "firstname":"Freddy",
        "lastname":"Mercury",
        "gender":"M"
    },
    { 
        "grade":12,
        "firstname":"Tessa",
        "lastname":"Thompson"
    }
]

df = pd.DataFrame(students)
df

The result is:

    firstname   gender  grade   lastname
0   Brendon M   5   Urie
1   Freddy  M   7   Mercury
2   Tessa   NaN 12  Thompson
Lamanus
  • 12,898
  • 4
  • 21
  • 47
0

If you mean tables for terminal terminaltables is just what you need :

https://robpol86.github.io/terminaltables/

Loïc
  • 11,804
  • 1
  • 31
  • 49
0

You can pretty-print dictionary as tables using tabulate

from tabulate import tabulate

def dict_to_list(lst):
  """ Converts students to list of the form 
[[5, 'Brendon', 'Urie', 'M'], [7, 'Freddy', 'Mercury', 'M'], ...] """
  return [[v for v in d.values()] for d in lst]

students = [ 
  { "grade": 5,
    "firstname": "Brendon", 
    "lastname": "Urie", 
    "gender": "M" 
    },
  { 
    "grade": 7,
    "firstname": "Freddy",
    "lastname": "Mercury",
    "gender": "M" 
  },
  { 
    "grade": 12,
    "firstname": "Tessa",
    "lastname": "Thompson"
  }
]

# tabulate takes as input: list of lists, and header
# list of list = dict_to_list(students)
# header = students[0].keys()
print (tabulate(dict_to_list(students), students[0].keys()))

Output (pretty format with columns aligned)

 grade  firstname    lastname    gender
-------  -----------  ----------  --------
      5  Brendon      Urie        M
      7  Freddy       Mercury     M
     12  Tessa        Thompson
DarrylG
  • 16,732
  • 2
  • 17
  • 23