我有这个子词典列表:
my_dict = [ {'type' : 'type_1', 'prob' : 2, 'x_sum' : 3, 'y_sum' : 5}
{'type' : 'type_2', 'prob' : 3, 'x_sum' : 8, 'y_sum' : 6}]
我想将其打印为表格:
type |prob|x_sum|y_sum
type_1|2 |3 |5
type_2|3 |8 |6
我试过这个解决方案:
for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):
print(*row)
但有错误: 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)
输出
type prob x_sum y_sum
0 type_1 2 3 5
1 type_2 3 8 6
没有索引列
df_no_indices = df.to_string(index=False)
print(df_no_indices)
输出
type prob x_sum y_sum
type_1 2 3 5
type_2 3 8 6
其他格式示例
邮政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 |
+----+--------+--------+---------+---------+
HTML
pdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='html')
print(pdtabulate(df))
<table>
<thead>
<tr><th style="text-align: right;"> </th><th>type </th><th style="text-align: right;"> prob</th><th style="text-align: right;"> x_sum</th><th style="text-align: right;"> y_sum</th></tr>
</thead>
<tbody>
<tr><td style="text-align: right;"> 0</td><td>type_1</td><td style="text-align: right;"> 2</td><td style="text-align: right;"> 3</td><td style="text-align: right;"> 5</td></tr>
<tr><td style="text-align: right;"> 1</td><td>type_2</td><td style="text-align: right;"> 3</td><td style="text-align: right;"> 8</td><td style="text-align: right;"> 6</td></tr>
</tbody>
</table>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句