python
[Python] Use json.dumps() to pretty-print Python dicts
# 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
Was this helpful?
Similar Posts
- Print DataFrame in pretty format in Terminal
- Use separator in print() method of python
- [Python] The get() method on Python dicts and its "default" arg
- Print whole month from calendar using python
- Use of else condition with for loop in Python
- Use of try, except, else and finally in python
- Learn to Use Python's Built-In String Functions