pprint dictionary on multiple lines
Asked Answered
L

5

101

I'm trying to get a pretty print of a dictionary, but I'm having no luck:

>>> import pprint
>>> a = {'first': 123, 'second': 456, 'third': {1:1, 2:2}}
>>> pprint.pprint(a)
{'first': 123, 'second': 456, 'third': {1: 1, 2: 2}}

I wanted the output to be on multiple lines, something like this:

{'first': 123,
 'second': 456,
 'third': {1: 1,
           2: 2}
}

Can pprint do this? If not, then which module does it? I'm using Python 2.7.3.

Lipread answered 24/11, 2013 at 5:19 Comment(2)
Does this answer your question? How to pretty print nested dictionaries?Henceforward
@Henceforward not quite. The desired output in that question is not the same as mine is hereLipread
A
124

Use width=1 or width=-1:

In [33]: pprint.pprint(a, width=1)
{'first': 123,
 'second': 456,
 'third': {1: 1,
           2: 2}}
Aristotelianism answered 24/11, 2013 at 5:23 Comment(4)
What do negative widths do?Dyche
@Tim: I just tried it, and it worked, but I don't know if that is documented somewhere.Aristotelianism
Negative widths don't do anything special. As the code goes along, it checks to see if the length of the partial output string is < width. Any negative width just means the answer will always be "no". A width of 0 will almost always (or maybe always - I don't care enough to think about perverse cases ;-)) do the same.Moribund
@TimPeters: Yeah, I took a look at the source. There is a check for width==0 (it raises an error), but it seems that 0 could be treated the same as a negative value--always answer "no", as you put it--with no harm.Aristotelianism
L
56

You could convert the dict to json through json.dumps(d, indent=4)

import json

print(json.dumps(item, indent=4))
{
    "second": 456,
    "third": {
        "1": 1,
        "2": 2
    },
    "first": 123
}
Literalminded answered 30/10, 2017 at 2:37 Comment(4)
Much prettier than the other solutionsPrescript
@ErikAronesty While you should pay attention to the null and boolean values (true/false). They are JSON values not the python objects.Literalminded
Okay solution for simple cases, but converts python values to json values (as @RyanChou pointed out) and it might not be desirable or possible (like with datetime): json.dumps({'d': datetime.now()}) will crash with Object of type datetime is not JSON serializable.Patty
NameError: name 'json' is not defined - Is this a module that needs importing? If so, would you mind updating your answer to reflect that?Ranson
H
28

If you are trying to pretty print the environment variables, use:

pprint.pprint(dict(os.environ), width=1)
Hutchings answered 6/5, 2014 at 14:12 Comment(0)
T
4

Two things to add on top of Ryan Chou's already very helpful answer:

  • pass the sort_keys argument for an easier visual grok on your dict, esp. if you're working with pre-3.6 Python (in which dictionaries are unordered)
print(json.dumps(item, indent=4, sort_keys=True))
"""
{
    "first": 123,
    "second": 456,
    "third": {
        "1": 1,
        "2": 2
    }
}
"""
  • dumps() will only work if the dictionary keys are primitives (strings, int, etc.)
Tambourin answered 15/3, 2019 at 9:43 Comment(1)
Neat! sort_keys is a great argument. Unfortunately, as you say not always applicable: TypeError: Object of type Tag is not JSON serializable...Emarie
P
-1

This is a Copy-Pasta for testing purposes and to help with a usage example.

from pprint import pprint  # I usually only need this module from the package. 

a = {'first': 123, 'second': 456, 'third': {1:1, 2:2}, 'zfourth': [{3:9, 7:8}, 'distribution'], 1:2344, 2:359832, 3:49738428, 4:'fourth', 5:{'dictionary':'of things', 'new':['l','i','s','t']}}

pprint(dict(a), indent=4, width=1)

# Wrap your variable in dict() function
# Optional: indent=4. for readability
# Required: width=1 for wrapping each item to its own row.
# Note: Default pprint is to sort the dictionary
# Note: This also auto-wraps anything sting that has spaces in it.  See 'of things' below.

# Documentation:  https://docs.python.org/3/library/pprint.html
# Examples:       https://pymotw.com/2/pprint/
# Blog:           https://realpython.com/python-pretty-print/

Provides the following result:

{   1: 2344,
    2: 359832,
    3: 49738428,
    4: 'fourth',
    5: {   'dictionary': 'of '
                         'things',
           'new': [   'l',
                      'i',
                      's',
                      't']},
    'first': 123,
    'second': 456,
    'third': {   1: 1,
                 2: 2},
    'zfourth': [   {   3: 9,
                       7: 8},
                   'distribution']}
Porphyria answered 14/1, 2023 at 15:18 Comment(2)
I don't understand how this is intended to a) answer the question; b) add any information that isn't thoroughly covered by existing answers.Diligence
This helps as it is just a different perspective with a copy paste option. As sometimes snippets do not exactly convey the point to new learners.Porphyria

© 2022 - 2025 — McMap. All rights reserved.