Created
May 9, 2019 15:36
-
-
Save ferminhg/aff6494363b45cc1f6d18fb6cdf8cd2a to your computer and use it in GitHub Desktop.
pretty-print dicts with json.dumps()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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