Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: serialize a dictionary into a simple html output

Tags:

python

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;

data:
   id:1
   title:home
   address:
           street: some road
           city: anycity
           postal:somepostal

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.

Solution 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):
    p=[]
    p.append('<ul>\n')
    for k,v in dictObj.iteritems():
        if isinstance(v, dict):
            p.append('<li>'+ k+ ':')
            p.append(printitems(v))
            p.append('</li>')
        else:
            p.append('<li>'+ k+ ':'+ v+ '</li>')
    p.append('</ul>\n')
    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.

like image 973
spidee Avatar asked Oct 14 '10 06:10

spidee


1 Answers

Here's my simple solution, It can handle any level of nested dictionary.

import json
temp_text = {'decision': {'date_time': None, 'decision_type': None},
             'not_received': {'date_time': '2019-04-15T19:18:43.825766'},
             'received': {'date_time': None},
             'rfi': {'date_time': None},
             'under_review': {'date_time': None}}
dict_text_for_html = json.dumps(
    temp_text, indent=4
).replace(' ', '&nbsp').replace(',\n', ',<br>').replace('\n', '<br>')

html view of python dict

like image 66
Vishal Gupta Avatar answered Sep 20 '22 12:09

Vishal Gupta