如何在类生成的字典每行结果后添加空行输出?
方法一:遍历字典逐个打印键值对
直接遍历目标字典的键值对,单独打印每一组,每对之间添加空行即可。@dataclass装饰的类默认会生成友好的字符串表示,直接打印实例就能完整显示所有字段。
示例代码:
from dataclasses import dataclass # 定义你的Info_Match类 @dataclass class Info_Match: # 替换成你实际的字段 match_id: int team_name: str result: str # 模拟从数据库构建的test字典 test = { "round1": Info_Match(1, "TeamA", "Win"), "round2": Info_Match(2, "TeamB", "Lose"), "round3": Info_Match(3, "TeamC", "Draw") } # 格式化打印 for key, item in test.items(): print(f"*键*: `{key}`") print(f"*值*: {item}") print() # 空行分隔
输出效果:
键:
round1
值: Info_Match(match_id=1, team_name='TeamA', result='Win')键:
round2
值: Info_Match(match_id=2, team_name='TeamB', result='Lose')键:
round3
值: Info_Match(match_id=3, team_name='TeamC', result='Draw')
方法二:转普通字典后结构化输出
如果需要更清晰的层级展示,可以用dataclasses.asdict()把每个Info_Match实例转为普通字典,再结合json.dumps()做格式化换行。
示例代码:
import json from dataclasses import dataclass, asdict @dataclass class Info_Match: match_id: int team_name: str result: str test = { "round1": Info_Match(1, "TeamA", "Win"), "round2": Info_Match(2, "TeamB", "Lose"), "round3": Info_Match(3, "TeamC", "Draw") } # 转换为普通字典结构 formatted_data = {k: asdict(v) for k, v in test.items()} # 逐个打印带缩进的内容 for key, value in formatted_data.items(): print(f"`{key}`:") print(json.dumps(value, indent=2, ensure_ascii=False)) print()
输出效果:
round1:
{
"match_id": 1,
"team_name": "TeamA",
"result": "Win"
}
round2:
{
"match_id": 2,
"team_name": "TeamB",
"result": "Lose"
}
round3:
{
"match_id": 3,
"team_name": "TeamC",
"result": "Draw"
}
避坑提示
之前出现的「丢失对应类实例值」问题,大多是因为错误提取了实例的单个属性,而非直接使用整个实例。直接遍历打印完整的Info_Match实例,就能保证所有字段都被输出。
内容的提问来源于stack exchange,提问作者user20812299

