3 回答
TA贡献1744条经验 获得超4个赞
您可以使用 pandas 将其打印为数据框。
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
TA贡献1868条经验 获得超4个赞
您可以使用表格将字典漂亮地打印为表格
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
TA贡献1765条经验 获得超5个赞
添加回答
举报