以紧凑的方式打印大型嵌套词典的结构,而不打印所有元素

2024-04-26 01:07:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的嵌套字典,我想打印它的结构和每个级别的一个示例元素。在

例如:

from collections import defaultdict
nested = defaultdict(dict)
for i in range(10):
  for j in range(20):
    nested['key'+str(i)]['subkey'+str(j)] = {'var1': 'value1', 'var2': 'value2'}

如果我用pprint打印这个,我将得到所有非常长的元素,部分输出如下:

^{pr2}$

是否有一种内置方式或库来在每个级别中只显示少数顶层元素,并用'...'来表示其余元素,从而以紧凑的方式显示整个字典?如下所示(也要打印'...'):

每一级只有一个示例的期望输出:

{'key0': {
  'subkey0': {
    'var1: 'value1', 
    '...'
    },
  '...'
  },
  '...'
}

对于列表,我找到了this solution,但没有找到任何嵌套字典的内容。在


Tags: infrom元素示例for字典方式range
1条回答
网友
1楼 · 发布于 2024-04-26 01:07:28

一个基本的解决方案是设置自己的嵌套函数,该函数将循环并检测值,以便只打印从每个值中找到的第一个项。因为字典是不排序的,这意味着它将随机选择一个。因此,如果你想让它智能地分离不同类型的例子,你的目标本身就很复杂。在

但基本功能是如何工作的:

def compact_print(d, indent=''):
    items = d.items()
    key, value = items[0]
    if not indent:
        print("{")

    if isinstance(value, dict):
        print(indent + "'{}': {{".format(key))
        compact_print(value, indent + ' ')
        print(indent + "'...'")
    else:
        print(indent + "'{}': '{}',".format(key, value))
        print(indent + "'...'")
    print(indent + "}")

这个嵌套函数只遍历它找到的所有dict并继续忽略它获取的第一个条目。您可以为带有elif isinstance(value, list)的列表添加处理,对于其他类型也是如此。在

对于示例输入,它将生成以下内容:

^{pr2}$

相关问题 更多 >