spidee spidee - 1 year ago 94
Python Question

python: serialize a dictionary into a simple html output

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 want to serialize it into html.

so if i had

{'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}}

want i want is that rendered in some form of readable html using lists or tables;

street: some road
city: anycity

now i know i can do

for key in dict.items
print dict[key]

but that wont dive into the child values and list each key, value pair when the key/value is a dictionary - ie the address dict.

Is their a module for python that is lightweight/fast that will do this nicely. or does anyone have any simple code they can paste that might do this.

All the solutions here were useful. pprint is no doubt the more stable means of printing the dictionary, though it falls short of returning anything near html. Though still printable.

I ended up with this for now:

def printitems(dictObj, indent=0):
for k,v in dictObj.iteritems():
if isinstance(v, dict):
p.append('<li>'+ k+ ':')
p.append('<li>'+ k+ ':'+ v+ '</li>')
return '\n'.join(p)

It converts the dict into unordered lists which is ok for now. some css and perhaps a little tweaking should make it readable.

Im going to reward the answer to the person that wrote the above code, i made a couple of small changes as the unordered lists were not nesting. I hope all agree that many of the solutions offered proved useful, But the above code renders a true html representation of a dictionary, even if crude.

Answer Source

The example made by pyfunc could easily be modified to generate simple nested html lists.

z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}}

def printItems(dictObj, indent):
    print '  '*indent + '<ul>\n'
    for k,v in dictObj.iteritems():
        if isinstance(v, dict):
            print '  '*indent , '<li>', k, ':', '</li>'
            printItems(v, indent+1)
            print ' '*indent , '<li>', k, ':', v, '</li>'
    print '  '*indent + '</ul>\n'


Not terribly pretty of course, but somewhere to start maybe. If all you want to do is visualize data, the pprint module really is good enough. You could just use the "pre" tag on the result from pprint and put that on your web page.

the pprint version would look something like this:

import pprint
z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}}

print '<pre>', pprint.pformat(z), '</pre>'

And the html output look something like this:

{'data': {'address': {'city': 'anycity',
                      'postal': 'somepostal',
                      'street': 'some road'},
          'id': 1,
          'title': 'home'}}

Which isn't that pretty, but it at least shows the data in a more structured way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download