[🐍PyTricks]: You can use "json.dumps()" to pretty-print Python dict

... (as an alternative to the "pprint" module)

# The standard string repr for dicts is hard to read:
>>> my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
>>> my_mapping
{'b': 42, 'c': 12648430. 'a': 23}  # 😞

# The "json" module can do a much better job:
>>> import json
>>> print(json.dumps(my_mapping, indent=4, sort_keys=True))
{
    "a": 23,
    "b": 42,
    "c": 12648430
}

# Note this only works with dicts containing
# primitive types (check out the "pprint" module):
>>> json.dumps({all: 'yup'})
TypeError: keys must be a string

In most cases I'd stick to the built-in "pprint" module though :-)

— Dan

If you think your friends would find this tip useful, please share it with them—I’d really appreciate it. Here's the link: View in browser

To make sure you keep getting these emails, please add info@realpython.com to your address book or whitelist us. Want out of the loop? Unsubscribe.

308 E. 5th Ave, Vancouver BC V5T 1H4

تعليقات