-1

In python 3.6.8 I want to have the output of a pprint not been printed to the screen (e.g stdout), but I want that output as a string in a variable.

I tried the following (complete example):

import io
import pprint

d = {'cell_type': 'code',
   'execution_count': None,
   'metadata': {'collapsed': True, 'trusted': True},
   'outputs': []
}
f = io.StringIO()
pprint.pprint(dict, f)
print(f.read())

but I just got an empty string. I was expecting an output

{'cell_type': 'code',
 'execution_count': None,
 'metadata': {'collapsed': True, 'trusted': True},
 'outputs': []}

instead.

Maybe there is an easier way to achieve this without streams?

In the end I want to compare two very complex dictionaries to see their differences. My idea: Generate a string version of the dict and compare that (with something like a bash diff).

Alex
  • 41,580
  • 88
  • 260
  • 469
  • 1
    Why dont you simply use `str_d = str(d)`? – luigigi Dec 10 '19 at 06:44
  • another solution is to use the json module. import json then use json.dumps(d) to get a string representation of your dict. – rmilletich Dec 10 '19 at 06:48
  • Because then I still have the one dict in one single piece of text, which I can hardly compare to another dict. – Alex Dec 10 '19 at 06:49
  • As I mentioned, I want to compare two dicts. And I have them already in two files, but they have one single line each (with length 20000). Comparing those files as they are is meaningless – Alex Dec 10 '19 at 06:50
  • @Alex You're comparing them yourself, manually? – AMC Dec 10 '19 at 07:18
  • Nope, I want a proper diff with a tool or a command or something – Alex Dec 10 '19 at 07:51

1 Answers1

3

You have not moved your file pointer prior to read.

f = io.StringIO()
pprint.pprint(d, f) # note: pass d and not dict
f.seek(0) # move pointer to start of file
print(f.read())

or just

print(f.getvalue())