Python Dictionary Variable Recursive Explorer

I've been collecting some data with Python, and the data is dictionary type. I want to know all the data that's contained in my dictionary item, but it was proving challenging because we have Level 1 keys, Level 2 keys, Level 3 keys and possibly more!

For example. Just for starters:

  • hostname
  • location
    • code
    • country
      • code
      • name
      • id
    • id

The following Python recursive definition (like Powershell function) will take as input a dictionary item, and list out all the keys, all the nested (embedded) keys, and the values of those keys.

def dictExplorer

def dictExplorer(*arg):
 d = arg[0]
 if len(arg) == 2:
  pfx = arg[1] + "."
  pfx = ""
 for k in list(d.keys()):
   dictExplorer(d[k], pfx + k)
    print(pfx + k + " = " + str(d[k]))
    print(pfx + k + " = None (NoneType)")


The usage is very simple. Say your dictionary item is the variable d:


The output is like:

key1 = value
key1.key2 = value
key1.key2.key3 = value