简体   繁体   English

如何在python中轻松显示顶级数据结构

[英]How to easily display top level of data structure in python

I am working with a (modestly) large complex structured data object in python. 我在python中使用(适度)大型复杂结构化数据对象。 It is something I've imported from json, so it's a hierarchical mixture of dicts and lists. 这是我从json导入的东西,所以它是dicts和列表的层次结构。 The data looks lovely in an online json-hierarchical browser. 数据在在线json分层浏览器中看起来很可爱。 However I have trouble navigating it in Python. 但是我在Python中导航它时遇到了麻烦。

If I type 如果我输入

pprint(data)

It gives me 30 pages of output in the console. 它在控制台中为我提供了30页的输出。 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 (eg each of which has several keys containing several lists of keys of lists), and at the lowest level there are numbers and strings. 因此,例如,如果我有一个dicts列表(例如,每个都有几个键包含几个列表的键列表),并且在最低级别有数字和字符串。

How can I show (in text form) just the higher-level part? 如何(以文本形式)显示更高级别的部分?

In the mean time I have resorted to an IDE which has a tree view. 与此同时,我采用了具有树视图的IDE。 But surely it's possible in the console? 但肯定有可能在控制台中? This must be a perennial problem - people need to do this all the time? 这一定是一个长期存在的问题 - 人们需要一直这样做吗?

Yep, pretty print does that; 是的,漂亮的印花就是这样; from the documentation , use the depth=n 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 that parameter directly to pprint.pprint: 您可以将该参数直接传递给pprint.pprint:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM