40

I'd like to use prettyprint to print out a dictionary, but into a string and not to console. This string is to be passed on to other functions.

I know I can use the "stream" parameter to specify a file instead of sys.out but I want a string.

How do I do that?

5
  • 23
    s=pprint.pformat(your_dict) Commented Feb 26, 2013 at 9:12
  • @thias that doesn't include newlines. Commented Feb 26, 2013 at 9:15
  • @Fabian yes it does. Simply specify the width parameter. Commented Feb 26, 2013 at 9:29
  • @Simon correct, my testing data was not big enough. Commented Feb 26, 2013 at 9:39
  • @eran can you please fix the correct answer? Commented Aug 15, 2021 at 7:11

3 Answers 3

106

You should simply call the pformat function from the pprint module:

import pprint
s = pprint.pformat(aDict)
Sign up to request clarification or add additional context in comments.

4 Comments

much more pythonic than going via StringIO, IMHO
I agree. I didn't know about this option of pprint.
This needs to be set as the correct answer since the request is for pprint as a string, pformat is the method for this. Its provided for exactly this purpose by the pprint module.
I wonder why this answer is not chosen as the correct answer
9

I sometimes use the json module for that:

In [1]: import json

In [2]: d = {'a':1, 'b':2, 'c':{'a':1}}

In [3]: s = json.dumps(d, indent=4)

In [4]: s
Out[4]: '{\n    "a": 1, \n    "c": {\n        "a": 1\n    }, \n    "b": 2\n}'

In [5]: print s
{
    "a": 1, 
    "c": {
        "a": 1
    }, 
    "b": 2
}

3 Comments

try d = {'a':1, 'b':2, 'c':{'a':[1,2,3,4]}}. I don't think it works well for arbitrary python objects as pprint does
@thias -- there are some limitations [has to be JSON serializable], but it works fine with the example you gave.
@thias -- with nested dicts I actually think it looks better from the aesthetic point of view :)
0

Just use the StringIO module:

import StringIO

output = StringIO.StringIO()

Now you may pass output as a stream to prettyprint.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.