python - 以表格格式打印嵌套字典

标签 python pandas dictionary nested

我正在尝试以表格格式打印我的嵌套字典。但一直未能如愿。该表是学生姓名和学生成绩的列表。我希望它采用易于阅读的“报告卡”类型格式。我正在使用的 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 |
    
  • pandas 优于其他实现的好处是,数据现在采用易于分析和绘图的格式。

  • 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')
    
    enter image description here

    关于python - 以表格格式打印嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65546197/

    相关文章:

    ios - Xcode 7.2.1 Swift 2.1.1 无法将类型 'Dictionary<_,_>' 的值分配给类型 'Dictionary'

    python - 'SparseTensor' 对象不是可订阅的 keras

    python - 为 python 应用程序定义不同的路由

    python - Tensorflow 对象检测 API ( TF 2.0) GPU 不工作

    python - 如何删除所有重复出现或在 Pandas 数据框中获取唯一值?

    python - python中的词频不起作用

    python - 为什么 Django 认为我的查询字符串是空的?

    python - 从 panda 数据框中的 ufloat 中提取名义偏差和标准偏差

    python - 了解 pandas 系列提取函数中的正则表达式

    Python:如何修改 for 循环中交替键的字典值?