1

I want to print dictionaries in a formatted way, so I tried to use prettyprinter. I wanted to get a result with separate line by each value, something like this:

[
    {
        "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
    },
...

but instead, I get something like this(please ignore values):

[ {'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},

my pformat call is this:

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

I am currently using python 3.9, and I've tried 3.10. On documentation, pformat should print each value separately when compact=False. What am I doing wrong?

me in let
  • 13
  • 3
  • Are you tied to using the `pformat` function? Because `json.dumps` from the `json` package does the job. – statnet22 Jul 27 '22 at 09:45
  • 1
    @statnet22 yes, I'm working on napalm driver project with other people, and some APIs have non-string key. – me in let Jul 27 '22 at 10:05
  • Ah, I see! Hmm, it seems this has been a problem for a while and that the `compact` argument just isn't set up to affect dictionaries. Take a look [here](https://bugs.python.org/issue34798). – statnet22 Jul 27 '22 at 10:18
  • 1
    @statnet22 oh, I see... guess I'll just have to write my own function... thank you – me in let Jul 28 '22 at 00:48

0 Answers0