我如何将输出放入表格中?

时间:2019-10-19 14:56:59

标签: python python-3.x list dictionary

我希望输出是表格。 没有大括号和双引号。我可以得到一些帮助吗?我正在使用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)

3 个答案:

答案 0 :(得分:1)

您可以使用熊猫将其打印为数据框。

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

结果是:

    firstname   gender  grade   lastname
0   Brendon M   5   Urie
1   Freddy  M   7   Mercury
2   Tessa   NaN 12  Thompson

答案 1 :(得分:0)

如果您的意思是终端terminaltables的表正是您所需要的:

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

答案 2 :(得分:0)

您可以使用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()))

输出(列对齐的漂亮格式)

 grade  firstname    lastname    gender
-------  -----------  ----------  --------
      5  Brendon      Urie        M
      7  Freddy       Mercury     M
     12  Tessa        Thompson