Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty print namedtuple

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

like image 785
bobzhang Avatar asked May 05 '15 20:05

bobzhang


People also ask

What is pretty print in Python?

The pprint module in Python is a utility module that you can use to print data structures in a readable, pretty way. It's a part of the standard library that's especially useful for debugging code dealing with API requests, large JSON files, and data in general.

Is NamedTuple faster than dictionary?

Dictionary lies between a plain tuple and a named tupled in terms of performance and readability. Named tuples clearly win in readability but lag in creation and access times. Plain tuples are fast to create and access but using indices 0, 1, 2 makes my head spin and I can actually mix them up.

Is NamedTuple slow?

NamedTuple is the faster one while creating data objects (2.01 µs). An object is slower than DataClass but faster than NamedTuple while creating data objects (2.34 µs).

How do I get NamedTuple value?

From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.


1 Answers

I use namedtuple's _asdict method.

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(busbar._asdict())) {'id': 102,  'name': 'FACTORY',  'voltage': 21.8} 
like image 179
Peter Wood Avatar answered Sep 21 '22 20:09

Peter Wood