Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

For example:

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 pretty print this using pprint, I'll get all the elements which is very long, part of the output will be like the following:

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 a library to show only few top elements in each level and represent the rest with '...' to show the whole dictionary in a compact way? Something like the following (the '...' is also to be printed):

Desired output 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.

like image 710
CentAu Avatar asked Sep 05 '16 16:09

CentAu


People also ask

How do I print a nested dictionary?

As others have posted, you can use recursion/dfs to print the nested dictionary data and call recursively if it is a dictionary; otherwise print the data.

How do you print a dictionary structure in Python?

Use pprint() to Pretty Print a Dictionary in Python Within the pprint module there is a function with the same name pprint() , which is the function used to pretty-print the given string or object. First, declare an array of dictionaries. Afterward, pretty print it using the function pprint.

How do you create an empty nested dictionary in Python?

In Python, we can use the zip() and len() methods to create an empty dictionary with keys. This method creates a dictionary of keys but returns no values from the dictionary.

How do you flatten nested dictionary?

Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step. For Python >= 3.3, change the import to from collections.


1 Answers

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.

But here's how the basic function could work:

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

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 elif isinstance(value, list), and likewise for other types.

For your sample input, it generates this:

{
'key9': {
 'subkey10': {
  'var1': 'value1',
  '...'
  }
 '...'
 }
'...'
}
like image 122
SuperBiasedMan Avatar answered Nov 08 '22 15:11

SuperBiasedMan