In IDLE, what is the simplest way to limit the number of lines displayed by a pprint call?

74 views Asked by At

I am working with large nested dictionaries in Python and would like to quickly check their structure in IDLE. The pprint module nicely displays this structure, but leads IDLE to hang due to the size the variables. Is there a simple way to limit the number of lines that pprint prints, or similarly limit the number of key-value pairs displayed at each level of structure? (I may be missing something obvious here.)

Of note, there appears to be a reprlib module made for the similar goal of truncating the output of print after a certain number of characters. However, print does not display the structure of large nested dictionaries in a readable fashion, so this module seems to be impractical for my purpose.

3

There are 3 answers

0
Kelly Bundy On BEST ANSWER

You could format the data to a string, split it into lines, and print only as many as desired:

for line in pprint.pformat(data).splitlines()[:42]:
    print(line)

Instead of slicing, you could also just print all lines and stop with Ctrl-C when you've seen enough.

1
Seaver On

I've been playing around with your problem. Would printing a truncated dictionary instead accomplish what you need? Here I applied a technique from tutorialsport

import itertools                                                                
import pprint                                                                   
                                                                                
# An arbitary, nested dictionary                                                
nested_inner = {i: ['a', 'b', 'c'] for i in range(5)}                           
nested_mid = {chr(i): nested_inner for i in range(65, 70)}                      
nested_outer = {i: nested_mid for i in range(10000)}                            
                                                                                
# truncate the dictionary instead?                                              
sample_data = dict(itertools.islice(nested_outer.items(), 500))                 
                                                                                
pprint.PrettyPrinter(indent=4, width=80, depth=3)                               
pprint.pprint(sample_data)
1
Seaver On

Have you tried either reducing the nesting by setting the depth parameter or setting compact=True? See https://docs.python.org/3/library/pprint.html