Skip to content

Instantly share code, notes, and snippets.

@ferminhg
Created May 9, 2019 15:36
Show Gist options
  • Select an option

  • Save ferminhg/aff6494363b45cc1f6d18fb6cdf8cd2a to your computer and use it in GitHub Desktop.

Select an option

Save ferminhg/aff6494363b45cc1f6d18fb6cdf8cd2a to your computer and use it in GitHub Desktop.
pretty-print dicts with json.dumps()
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment