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

前端 未结 11 1356
小鲜肉
小鲜肉 2020-12-10 00:19

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 afte

11条回答
  •  生来不讨喜
    2020-12-10 01:03

    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
    ]
    

提交回复
热议问题