python: serialize a dictionary into a simple html output

前端 未结 9 763
轮回少年
轮回少年 2021-01-12 00:59

using app engine - yes i know all about django templates and other template engines.

Lets say i have a dictionary or a simple object, i dont know its structure and i

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 01:20

    You could use pretty print (pprint)

    or if you want to do some further processing of display then you have to run through the dict yourself.

    Be warned that the code is crude and will require numerous refinements. Solution uses recursion too, which is bad, if the recursion depth is higher.

    z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal', 'telephone':{'home':'xxx','offie':'yyy'}}}}
    
    def printItems(dictObj, indent):
        it = dictObj.iteritems()
        for k,v in it:
            if isinstance(v, dict):
                print ' '*indent , k, ':'
                printItems(v, indent+1)
            else:
                print ' '*indent , k, ':', v
    
    printItems(z,0)
    

    Output:

     data :
      address :
       city : anycity
       postal : somepostal
       street : some road
       telephone :
        home : xxx
        offie : yyy
      id : 1
      title : home
    

提交回复
热议问题