Pretty print namedtuple

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’: … Read more

Disabling sorting mechanism in pprint output

Python 3.8 or newer: Use sort_dicts=False: pprint.pprint(data, sort_dicts=False) Python 3.7 or older: You can monkey patch the pprint module. import pprint pprint.pprint({“def”:2,”ghi”:3,”abc”:1,}) pprint._sorted = lambda x:x # Or, for Python 3.7: # pprint.sorted = lambda x, key=None: x pprint.pprint({“def”:2,”ghi”:3, “abc”:1}) Since the 2nd output is essentiallly randomly sorted, your output may be different from mine: … Read more

Any way to properly pretty-print OrderedDict?

Ever since Python 3.7, Python guarantees that keys in a dictionary will retain their insertion order. (They still don’t behave exactly the same as OrderedDict objects, though, as two dicts a and b can be considered equal a == b even if the order of the keys is different, whereas OrderedDict does check this upon … Read more

How do I get python’s pprint to return a string instead of printing?

The pprint module has a function named pformat, for just that purpose. From the documentation: Return the formatted representation of object as a string. indent, width and depth will be passed to the PrettyPrinter constructor as formatting parameters. Example: >>> import pprint >>> people = [ … {“first”: “Brian”, “last”: “Kernighan”}, … {“first”: “Dennis”, “last”: … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)