You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python pformat设置compact=False未生效?字典格式化异常

问题描述

我想用pformat格式化打印字典列表,期望每个字典的键值对单独换行,示例输出如下:

[
    {
        "interface": "mgmt0",
        "mac": "00:07:70:E6:51:BA",
        "ip": "10.4.12.254",
        "age": -1.0
    },
    {
        "interface": "Vlan50",
        "mac": "70:30:5D:5B:DA:27",
        "ip": "53.1.1.2",
        "age": 67214.0
    },
...

但实际输出中每个字典都挤在一行:

[ {'interface': 'Vlan4001', 'mac': '70:30:5D:50:99:99', 'ip': '10.4.12.27', 'age': -1.0},
  {'interface': 'Vlan4001', 'mac': 'C8:5A:CF:BA:F5:74', 'ip': '10.4.12.183', 'age': -1.0},
  {'interface': 'Vlan4001', 'mac': 'A8:E5:39:A7:0D:28', 'ip': '10.4.12.185', 'age': -1.0},
  {'interface': 'Vlan4001', 'mac': '14:CB:19:68:0D:77', 'ip': '10.4.12.204', 'age': -1.0},
  {'interface': 'Vlan4001', 'mac': '98:83:89:A2:A6:C4', 'ip': '10.4.12.212', 'age': -1.0},

我的调用代码为:

ret = pformat(ret, indent=2, sort_dicts=False, width=250, compact=False)

使用Python 3.9和3.10版本,按文档说明compact=False应让每个值单独换行,请问哪里操作有误?

解决方法

问题出在width=250的设置上。pformat会先判断单行内容长度是否超过指定的width阈值,只有当单行长度超过阈值时,才会触发键值对的换行拆分。你的每个字典单行长度远小于250,所以工具会默认将整个字典放在一行显示。

调整方案有两种:

  • 降低width的值,让单行无法容纳整个字典,强制拆分键值对,比如设置width=40:
ret = pformat(ret, indent=2, sort_dicts=False, width=40, compact=False)
  • 直接使用pprint.pprint方法打印,它的默认行为更贴合你的需求,无需手动调整过多参数:
import pprint
pprint.pprint(ret, indent=2, sort_dicts=False)

内容的提问来源于stack exchange,提问作者me in let

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:06:35