Print the structure of large nested dictionaries in a compact way without printing all elements
<p>I have a large nested dictionary and I want to print its structure and one sample element in each level. </p>

<p>For example:</p>

<pre><code>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'}
</code></pre>

<p>If I pretty print this using <code>pprint</code>, I'll get all the elements which is very long, part of the output will be like the following:</p>

<pre><code>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'},
</code></pre>

<p>Is there a built-in way or a library to show only few top elements in each level and represent the rest with <code>'...'</code> to show the whole dictionary in a compact way? Something like the following (the <code>'...'</code> is also to be printed):</p>

<p>Desired output with only 1 example at each level:</p>

<pre><code>{'key0': {
  'subkey0': {
    'var1: 'value1', 
    '...'
    },
  '...'
  },
  '...'
}
</code></pre>

<p>For lists, I found <a href="http://stackoverflow.com/questions/38533282/python-pretty-print-dictionary-of-lists-abbreviate-long-lists">this solution</a>, but I did not find anything for nested dictionaries.</p>

<p>A basic solution is to just set up your own nested function that will loop through and detect values to print only the first item it finds from each. Since dictionaries aren't ordered, this does mean it will randomly pick one. So your goal is inherently complicated if you want it to intelligently separate different types of example.</p>

<p>But here's how the basic function could work:</p>

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

<p>This nested function just iterates down through any dicts it finds and continues ignoring past the first item it grabs. You could add handling for lists with an <code>elif isinstance(value, list)</code>, and likewise for other types.</p>

<p>For your sample input, it generates this:</p>

<pre><code>{
'key9': {
 'subkey10': {
  'var1': 'value1',
  '...'
  }
 '...'
 }
'...'
}
</code></pre>

python dictionary printing