Python: Pretty Print in Jupyter Notebook
Asked Answered
S

3

20

I am trying to pretty print a dict in Jupyter Notebook.

I am using the following:

import pprint
stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
stuff.insert(0, stuff[:])
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(stuff)

However upon pressing shift+enter, no [out] cell appear (i.e. I can't see the pretty printed output)

enter image description here

Any idea why this is so/ what should I change in order to see the pretty printed output?


Edit: Actually this is a python 2.7 problem - it works fine in 3.x. Have anyone tried it on python 2.7 and seen it work?

Sonny answered 27/2, 2017 at 1:9 Comment(6)
The same code works fine for me. I am using Python 3.6Estrone
@Estrone Oh I see - I am using 2.7... Do you have any idea what would be the coreect syntax in 2.7 ?Sonny
I tested your code on try.jupyter.org and it did show output.Batrachian
you could try outputting html, as pretty as you wish: #25698948Elijaheliminate
@jimbasquiat Yes it works on 2.7Soubrette
Also working here. Cannot reproduceTwyla
T
7

Whatever you develop is correct. The only possible reason could be, Jupyter Notebook is unable to connect to the server. If you see connecting to Kernal/server like the image below in the toolbar, try to refresh the connection or reload the page.

enter image description here

I used the same code and I am able to see the output. check the image below.

enter image description here

Triolein answered 27/2, 2017 at 1:29 Comment(0)
A
0

I had this problem with Python 3, in my case solved removing an AD block extension.. somehow it was blocking the AJAX request that set the output..

Amadaamadas answered 2/3, 2021 at 2:51 Comment(0)
A
0

The title is generic to more than dict in Jupyter, so i give a generic answer.

When printing, change this

print(longValue, nextValue)

to this (have to try with other values than 30)

space = (30-len(longValue)*" "
print(longValue,space,nextValue)

That will change this

enter image description here

Into this

enter image description here

Arria answered 15/11, 2021 at 10:40 Comment(1)
Easier to let Python calculate the spaces for you with: print("{:30s} {:s} ".format(longVal, nextVal))Ectogenous

© 2022 - 2024 — McMap. All rights reserved.