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
etcetera...
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] + "."
else:
pfx = ""
for k in list(d.keys()):
try:
dictExplorer(d[k], pfx + k)
except:
try:
print(pfx + k + " = " + str(d[k]))
except:
print(pfx + k + " = None (NoneType)")
Usage
The usage is very simple. Say your dictionary item is the variable d:
dictExplorer(d)
The output is like:
key1 = value
key1.key2 = value
key1.key2.key3 = value
Comments
Post a Comment