How to easily display top level data structure in python

I work with a (modestly) large complex structured data object in python. This is what I imported from json, so this is a hierarchical mixture of dicts and lists. The data looks great in an online hierarchical browser. However, I have problems navigating in Python.

If i type

pprint(data)

It gives me 30 pages of output in the console. What if I just want to list, for example, the top two levels of the tree? So, for example, if I have a list of dicts (for example, each of which has several keys containing several lists of list keys), and at the lowest level there are numbers and strings.

How can I show (in text form) only a part of a higher level?

At the same time, I resorted to an IDE with a tree. But of course, is this possible in the console? It must be a constant problem - do people need to do this all the time?

+4
source share
1 answer

Yes, it pretty prints; from the documentation , use the keyword parameter depth = n:

>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))

You can pass this parameter directly to pprint.pprint:

>>> pprint.pprint(tup, depth=6)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
+5
source

Source: https://habr.com/ru/post/1613852/


All Articles