A more generalized solution that processes arbitrarily deeply nested dictations and lists:
def dumpclean(obj): if isinstance(obj, dict): for k, v in obj.items(): if hasattr(v, '__iter__'): print k dumpclean(v) else: print '%s : %s' % (k, v) elif isinstance(obj, list): for v in obj: if hasattr(v, '__iter__'): dumpclean(v) else: print v else: print obj
This produces the conclusion:
A color : 2 speed : 70 B color : 3 speed : 60
I ran into a similar need and developed a more robust feature for myself. I include this here, in case this may matter to another. While checking the nose, I also found it useful to specify the output stream in the call so that sys.stderr could be used instead.
import sys def dump(obj, nested_level=0, output=sys.stdout): spacing = ' ' if isinstance(obj, dict): print >> output, '%s{' % ((nested_level) * spacing) for k, v in obj.items(): if hasattr(v, '__iter__'): print >> output, '%s%s:' % ((nested_level + 1) * spacing, k) dump(v, nested_level + 1, output) else: print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v) print >> output, '%s}' % (nested_level * spacing) elif isinstance(obj, list): print >> output, '%s[' % ((nested_level) * spacing) for v in obj: if hasattr(v, '__iter__'): dump(v, nested_level + 1, output) else: print >> output, '%s%s' % ((nested_level + 1) * spacing, v) print >> output, '%s]' % ((nested_level) * spacing) else: print >> output, '%s%s' % (nested_level * spacing, obj)
Using this function, the OP output is as follows:
{ A: { color: 2 speed: 70 } B: { color: 3 speed: 60 } }
which I personally found more useful and descriptive.
Given a slightly less trivial example:
{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}
The requested OP solution gives this:
test 1 : 3 test3 (1, 2) abc def ghi (4, 5) : def test2 (1, 2) (3, 4)
whereas the "improved" version gives the following:
{ test: [ { 1: 3 } ] test3: { (1, 2): [ abc def ghi ] (4, 5): def } test2: [ (1, 2) (3, 4) ] }
I hope this gives some value to the next person looking for this type of functionality.