Pretty print namedtuple

bobzhang picture bobzhang · May 5, 2015 · Viewed 8.2k times · Source

I tried pprint from pprint, but its output is just one line, there is no multiline output and no indentation.

Answer

Peter Wood picture Peter Wood · May 5, 2015

I use the builtin function vars to get the namedtuple as a dictionary.

However, it returns an OrderedDict which pprint won't indent, so I convert it to a dict:

>>> from collections import namedtuple

>>> Busbar = namedtuple('Busbar', 'id name voltage')
>>> busbar = Busbar(id=102, name='FACTORY', voltage=21.8)

With pprint and dict:

>>> from pprint import pprint
>>> pprint(dict(vars(busbar)))
{'id': 102,
 'name': 'FACTORY',
 'voltage': 21.8}