如何在传入字典列表时使用tabulate.SEPARATING_LINE?
关于tabulate中字典列表使用SEPARATING_LINE的问题
问题背景
使用tabulate库时,列表形式插入tabulate.SEPARATING_LINE可以正常生成分隔线,但在字典列表中直接插入该常量会报错,期望字典列表也能生成和列表形式一致的短横线分隔线。
列表形式正常运行示例
import tabulate print(tabulate.tabulate([["A", 200], ["B", 100], tabulate.SEPARATING_LINE, ["Total", 4]], headers=["Col1", "Col2"]))
输出:
Col1 Col2 ------ ------ A 200 B 100 ------ ------ Total 4
未添加分隔线的字典列表示例
print( tabulate.tabulate( [ {"Col1": "A", "Col2": 200}, {"Col1": "B", "Col2": 100}, #tabulate.SEPARATING_LINE, {"Col1": "TOTAL", "Col2": 200}, ], headers="keys", ) )
输出:
Col1 Col2 ------ ------ A 200 B 100 TOTAL 200
添加分隔线后的报错信息
直接插入tabulate.SEPARATING_LINE会抛出以下错误:
Traceback (most recent call last): File "/home/raul/python-playground/tabulates1.py", line 8, in <module> tabulate.tabulate( File "/home/raul/.venv/lib/python3.11/site-packages/tabulate/__init__.py", line 2048, in tabulate list_of_lists, headers = _normalize_tabular_data( ^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raul/.venv/lib/python3.11/site-packages/tabulate/__init__.py", line 1409, in _normalize_tabular_data for k in row.keys(): ^^^^^^^^ AttributeError: 'str' object has no attribute 'keys'
解答
核心结论
tabulate.SEPARATING_LINE目前不支持直接插入字典列表。
原因分析
SEPARATING_LINE本质是一个字符串常量(值为'---'),当tabulate处理字典列表时,会默认遍历每个元素的keys()方法来匹配表头和行数据,字符串没有该方法,因此触发AttributeError。
可行解决方案
方案1:转换为普通列表后插入分隔线
先将字典列表按表头顺序转换为普通列表,再插入SEPARATING_LINE,示例代码:
import tabulate data_dicts = [ {"Col1": "A", "Col2": 200}, {"Col1": "B", "Col2": 100}, {"Col1": "TOTAL", "Col2": 200}, ] headers = ["Col1", "Col2"] # 把字典转成对应表头顺序的列表 data_lists = [[d[col] for col in headers] for d in data_dicts] # 在指定位置插入分隔线 data_lists.insert(2, tabulate.SEPARATING_LINE) print(tabulate.tabulate(data_lists, headers=headers))
输出与列表形式一致:
Col1 Col2 ------ ------ A 200 B 100 ------ ------ TOTAL 200
方案2:手动构造分隔线字典
如果不想转换列表,可以构造一个所有值为分隔线字符串的字典,配合合适的tablefmt参数模拟分隔效果,示例:
import tabulate print( tabulate.tabulate( [ {"Col1": "A", "Col2": 200}, {"Col1": "B", "Col2": 100}, {"Col1": "------", "Col2": "------"}, {"Col1": "TOTAL", "Col2": 200}, ], headers="keys", tablefmt="simple" ) )
输出:
Col1 Col2 ------ ------ A 200 B 100 ------ ------ TOTAL 200
注意:这种方法需要根据表格列宽调整分隔线长度,不同tablefmt可能需要适配。
内容的提问来源于stack exchange,提问作者Raúl Salinas-Monteagudo
相关产品推荐
相关产品推荐

