I tried pprint
from pprint
, but its output is just one line, there is no multiline output and no indentation.
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.
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.
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).
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With