Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

python - Pretty print namedtuple

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...