Print the structure of large nested dictionaries in a compact way without printing all the elements

I have a large nested dictionary, and I want to print its structure and one sample element at each level.

For instance:

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'}

If I am pretty printing this with pprint, I will get all the elements that are very long, part of the output will look like this:

from pprint import pprint
pprint(nested)

        {'key0': {'subkey0': {'var1': 'value1', 'var2': 'value2'},
          'subkey1': {'var1': 'value1', 'var2': 'value2'},
          'subkey10': {'var1': 'value1', 'var2': 'value2'},
          'subkey11': {'var1': 'value1', 'var2': 'value2'},
          'subkey12': {'var1': 'value1', 'var2': 'value2'},
          'subkey13': {'var1': 'value1', 'var2': 'value2'},
          'subkey14': {'var1': 'value1', 'var2': 'value2'},

Is there a built-in way or library to display only a few top elements at each level and represent the rest using '...'to show the entire dictionary in a compact way? Something like the following (should also be printed '...'):

Desired conclusion with only 1 example at each level:

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

For lists, I found this solution , but I did not find anything for nested dictionaries.

+4
1

, , , . , , . , , , .

:

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 + "}")

dicts, , , . elif isinstance(value, list), .

:

{
'key9': {
 'subkey10': {
  'var1': 'value1',
  '...'
  }
 '...'
 }
'...'
}
+1

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


All Articles