我有这个子词典列表:
my_dict = [ {'type' : 'type_1', 'prob' : 2, 'x_sum' : 3, 'y_sum' : 5}
{'type' : 'type_2', 'prob' : 3, 'x_sum' : 8, 'y_sum' : 6}]
Run Code Online (Sandbox Code Playgroud)
我想要将其打印为表格:
type |prob|x_sum|y_sum
type_1|2 |3 |5
type_2|3 |8 |6
Run Code Online (Sandbox Code Playgroud)
我尝试了这个解决方案:
for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):
print(*row)
Run Code Online (Sandbox Code Playgroud)
但出现错误: AttributeError: 'list' object has no attribute 'items' 如何解决列表问题?
最简单的方法是按照描述使用 Pandas将字典列表转换为数据框
代码
import pandas as pd
my_dict = [ {'type' : 'type_1', 'prob' : 2, 'x_sum' : 3, 'y_sum' : 5},
{'type' : 'type_2', 'prob' : 3, 'x_sum' : 8, 'y_sum' : 6}]
df = pd.DataFrame(my_dict)
print(df)
Run Code Online (Sandbox Code Playgroud)
输出
type prob x_sum y_sum
0 type_1 2 3 5
1 type_2 3 8 6
Run Code Online (Sandbox Code Playgroud)
无索引列
df_no_indices = df.to_string(index=False)
print(df_no_indices)
Run Code Online (Sandbox Code Playgroud)
输出
type prob x_sum y_sum
type_1 2 3 5
type_2 3 8 6
Run Code Online (Sandbox Code Playgroud)
其他格式示例
后SQL
from tabulate import tabulate
pdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='psql')
print(pdtabulate(df))
+----+--------+--------+---------+---------+
| | type | prob | x_sum | y_sum |
|----+--------+--------+---------+---------|
| 0 | type_1 | 2 | 3 | 5 |
| 1 | type_2 | 3 | 8 | 6 |
+----+--------+--------+---------+---------+
Run Code Online (Sandbox Code Playgroud)
超文本标记语言
pdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='html')
print(pdtabulate(df))
Run Code Online (Sandbox Code Playgroud)
import pandas as pd
my_dict = [ {'type' : 'type_1', 'prob' : 2, 'x_sum' : 3, 'y_sum' : 5},
{'type' : 'type_2', 'prob' : 3, 'x_sum' : 8, 'y_sum' : 6}]
df = pd.DataFrame(my_dict)
print(df)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7264 次 |
| 最近记录: |