Is there a Python equivalent to Perl's Data::Dumper for inspecting data structures?

Is there a Python module that can be used in the same way as Perl's Data::Dumper module?

Edit: Sorry, I should have been clearer. I was mainly after a module for inspecting data rather than persisting.

BTW Thanks for the answers. This is one awesome site!


Solution 1:

Data::Dumper has two main uses: data persistence and debugging/inspecting objects. As far as I know, there isn't anything that's going to work exactly the same as Data::Dumper.

I use pickle for data persistence.

I use pprint to visually inspect my objects / debug.

Solution 2:

I think the closest you will find is the pprint module.

>>> l = [1, 2, 3, 4]
>>> l.append(l)
>>> d = {1: l, 2: 'this is a string'}
>>> print d
{1: [1, 2, 3, 4, [...]], 2: 'this is a string'}

>>> pprint.pprint(d)
{1: [1, 2, 3, 4, <Recursion on list with id=47898714920216>],
 2: 'this is a string'}

Solution 3:

Possibly a couple of alternatives: pickle, marshal, shelve.

Solution 4:

I too have been using Data::Dumper for quite some time and have gotten used to its way of displaying nicely formatted complex data structures. pprint as mentioned above does a pretty decent job, but I didn't quite like its formatting style. That plus pprint doesn't allow you to inspect objects like Data::Dumper does:

Searched on the net and came across these:

https://gist.github.com/1071857#file_dumper.pyamazon

>>> y = { 1: [1,2,3], 2: [{'a':1},{'b':2}]}

>>> pp = pprint.PrettyPrinter(indent = 4)
>>> pp.pprint(y)
{   1: [1, 2, 3], 2: [{   'a': 1}, {   'b': 2}]}

>>> print(Dumper.dump(y)) # Dumper is the python module in the above link
{
    1: [
        1 
        2 
        3
    ] 
    2: [
        {
            'a': 1
        } 
        {
            'b': 2
        }
    ]
}
>>> print(Dumper.dump(pp))
instance::pprint.PrettyPrinter
    __dict__ :: {
        '_depth': None 
        '_stream': file:: > 
        '_width': 80 
        '_indent_per_level': 4
    }

Also worth checking is http://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py It has its own style and seems useful too.

Solution 5:

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
]