Here is a simple solution for dumping nested data made up of dictionaries, lists, or tuples (it works quite well for me):
Python2
def printStruct(struc, indent=0):
if isinstance(struc, dict):
print ' '*indent+'{'
for key,val in struc.iteritems():
if isinstance(val, (dict, list, tuple)):
print ' '*(indent+1) + str(key) + '=> '
printStruct(val, indent+2)
else:
print ' '*(indent+1) + str(key) + '=> ' + str(val)
print ' '*indent+'}'
elif isinstance(struc, list):
print ' '*indent + '['
for item in struc:
printStruct(item, indent+1)
print ' '*indent + ']'
elif isinstance(struc, tuple):
print ' '*indent + '('
for item in struc:
printStruct(item, indent+1)
print ' '*indent + ')'
else: print ' '*indent + str(struc)
Python3
def printStruct(struc, indent=0):
if isinstance(struc, dict):
print (' '*indent+'{')
for key,val in struc.items():
if isinstance(val, (dict, list, tuple)):
print (' '*(indent+1) + str(key) + '=> ')
printStruct(val, indent+2)
else:
print (' '*(indent+1) + str(key) + '=> ' + str(val))
print (' '*indent+'}')
elif isinstance(struc, list):
print (' '*indent + '[')
for item in struc:
printStruct(item, indent+1)
print (' '*indent + ']')
elif isinstance(struc, tuple):
print (' '*indent + '(')
for item in struc:
printStruct(item, indent+1)
print (' '*indent + ')')
else: print (' '*indent + str(struc))
See it at work:
>>> d = [{'a1':1, 'a2':2, 'a3':3}, [1,2,3], [{'b1':1, 'b2':2}, {'c1':1}], 'd1', 'd2', 'd3']
>>> printStruct(d)
[
{
a1=> 1
a3=> 3
a2=> 2
}
[
1
2
3
]
[
{
b1=> 1
b2=> 2
}
{
c1=> 1
}
]
d1
d2
d3
]