我正在尝试以表格格式打印我的嵌套字典。但一直未能如愿。该表是学生姓名和学生成绩的列表。我希望它采用易于阅读的“报告卡”类型格式。我正在使用的 for 循环打印出结果。但它是一列列表形式。
这是我设置的当前字典。
student = {
"student1": {
"Name": "Eddy",
"Grade": 1,
"Math": 78,
"English": 65,
"Physics": 89,
"Chemistry": 80
},
"student2": {
"Name": "Jim",
"Grade": 2,
"Math": 89,
"English": 65,
"Physics": 87,
"Chemistry": 76
},
"student3": {
"Name": "Jane",
"Grade": 3,
"Math": 87,
"English": 97,
"Physics": 75,
"Chemistry": 64
},
}
这是我目前使用的 for 循环。for i in student:
for j in student[i]:
print(j + " : " + str(student[i][j]))
print("===========")
我想以表格格式打印出来。Name Grade Math English Physics Chemistry
Eddy 1 78 65 89 80
Jim 2 89 65 87 76
Jane 3 87 97 75 64
我曾尝试使用 format()
函数,但无法使其与嵌套字典一起使用。我也尝试使用
pandas
并转换为 pd.DataFrame
,但无法使其工作。
最佳答案
这是一个 pandas解决方案,正如您提到的尝试 Pandas 失败。您可以使用 pandas.DataFrame.from_dict
与 orient=index
.
import pandas as pd
df = pd.DataFrame.from_dict(student, orient='index').reset_index(drop=True)
你得到 Name Grade Math English Physics Chemistry
0 Eddy 1 78 65 89 80
1 Jim 2 89 65 87 76
2 Jane 3 87 97 75 64
对于 markdown
table pandas.DataFrame.to_markdown()
print(df.to_markdown(index=False))
| Name | Grade | Math | English | Physics | Chemistry |
|:-------|--------:|-------:|----------:|----------:|------------:|
| Eddy | 1 | 78 | 65 | 89 | 80 |
| Jim | 2 | 89 | 65 | 87 | 76 |
| Jane | 3 | 87 | 97 | 75 | 64 |
import matplotlib.pyplot as plt
df.plot.barh(x='Name', y=['Math', 'English', 'Physics', 'Chemistry'], figsize=(6, 8))
plt.xlabel('Score')
plt.legend(title='Subject', bbox_to_anchor=(1.05, 1), loc='upper left')
关于python - 以表格格式打印嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65546197/