Python: serialize a dictionary into plain html output

using the application engine - yes, I know everything about django templates and other template mechanisms.

Let's say I have a dictionary or a simple object, I don’t know its structure, and I want to serialize it in html.

so if i had

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

want, I want, this is visualized 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 what i can do

 for key in dict.items print dict[key] 

but they will not plunge into child values ​​and enumerate each key pair when the key / value is a dictionary, that is, the dict address.

Is their module for python, which is easy / fast, which will make it beautiful. or does anyone have a simple code that they can insert that can do this.

Solution All the solutions here were helpful. pprint is without a doubt a more stable means of printing a dictionary, although it has nothing to return about html. Although you can still print.

I am done with this 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 are currently in order. some css and maybe a little tweak should make it readable.

I'm going to reward the answer to the person who wrote the code above, I made a couple of small changes, because the unordered lists were not nested. I hope everyone agrees that many of the proposed solutions have proven useful, but the code above displays the true html representation of the dictionary, even if it's rude.

+6
python
source share
9 answers

The example made by pyfunc can be easily modified to create 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) else: print ' '*indent , '<li>', k, ':', v, '</li>' print ' '*indent + '</ul>\n' printItems(z,0) 

Not scary, of course, but somewhere to start, maybe. If all you want to do is visualize the data, the pprint module is really good enough. You can simply use the "pre" tag for the result from pprint and place it on your web page.

The pprint version will 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 looks something like this:

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

Which is not , which is pretty, but at least it shows the data in a more structured way.

+8
source share
 import pprint pprint.pprint(yourDict) 

Well, no HTML, but it looks like your for/print approach.

EDIT: or use:

 niceText = pprint.pformat(yourDict) 

this will give you the same nice conclusion with all the indentation, etc. Now you can iterate over the lines and format them in HTML:

 htmlLines = [] for textLine in pprint.pformat(yourDict).splitlines(): htmlLines.append('<br/>%s' % textLine) # or something even nicer htmlText = '\n'.join(htmlLines) 
+5
source share

Take a look at my implementation:

 def pretty_items(r, d, nametag="<strong>%s: </strong>", itemtag='<li>%s</li>', valuetag="%s", blocktag=('<ul>', '</ul>')): if isinstance(d, dict): r.append(blocktag[0]) for k, v in d.iteritems(): name = nametag % k if isinstance(v, dict) or isinstance(v, list): r.append(itemtag % name) pretty_items(r, v) else: value = valuetag % v r.append(itemtag % (name + value)) r.append(blocktag[1]) elif isinstance(d, list): r.append(blocktag[0]) for i in d: if isinstance(i, dict) or isinstance(i, list): r.append(itemtag % " - ") pretty_items(r, i) else: r.append(itemtag % i) r.append(blocktag[1]) 

List all HTML elements using the <ul> and <li> tags. And also it is not necessary to change tags. And then just use CSS to handle indentation.

+2
source share

You can use pretty printed (pprint)

or if you want to do some further display processing, then you have to scroll through the dict itself.

It should be warned that the code is coarse and will require numerous refinements. The solution also uses recursion, 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 
+1
source share

I needed something similar, but also wanted nice print lists and lists inside the dict. Here is what I came up with:

 def format(self, obj, indent = 1): if isinstance(obj, list): htmls = [] for k in obj: htmls.append(self.format(k,indent+1)) return '[<div style="margin-left: %dem">%s</div>]' % (indent, ',<br>'.join(htmls)) if isinstance(obj, dict): htmls = [] for k,v in obj.iteritems(): htmls.append("<span style='font-style: italic; color: #888'>%s</span>: %s" % (k,self.format(v,indent+1))) return '{<div style="margin-left: %dem">%s</div>}' % (indent, ',<br>'.join(htmls)) return str(obj) 

Then, if you use webapp on appengine, you can simply do the following:

 self.response.out.write(self.format(obj)) 

This is an example output:

enter image description here

+1
source share

Here is my simple solution, it can handle any level of dictionary nesting.

 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 Python dict

+1
source share

imagine that we have this: {name: "a", children:[{name: "b", children: [] },{..},{..}]

 def ConvertDictToUlLi(): jsonResult = GetSomeRecursiveDict() def CreateHtml(DictItem, output): output = "<li>"+DictItem["name"] if jsonResult.has_key("name") else " " if len(DictItem["children"]) > 0: output = output + "<ul>" for item in DictItem["children"]: output = output + " "+CreateHtml(item, output)+" " output = output + "</ul>" return output+"</li>" result = "<ul class='tree'>"+CreateHtml(jsonResult, "")+"</ul>" return result 
0
source share

None of the above examples give good results, so I wrote two of my own functions that create a beautiful html look for dictionaries.

 def dict_to_html(dd, level=0): """ Convert dict to html using basic html tags """ import simplejson text = '' for k, v in dd.iteritems(): text += '<br>' + '&nbsp;'*(4*level) + '<b>%s</b>: %s' % (k, dict_to_html(v, level+1) if isinstance(v, dict) else (simplejson.dumps(v) if isinstance(v, list) else v)) return text def dict_to_html_ul(dd, level=0): """ Convert dict to html using ul/li tags """ import simplejson text = '<ul>' for k, v in dd.iteritems(): text += '<li><b>%s</b>: %s</li>' % (k, dict_to_html_ul(v, level+1) if isinstance(v, dict) else (simplejson.dumps(v) if isinstance(v, list) else v)) text += '</ul>' return text 
0
source share

Here is my version with list support ( labels are the detailed names of keys in the dictionary):

 def render_value(value, labels): if isinstance(value, (list, tuple)): return render_list(value, labels) elif isinstance(value, dict): return render_dict(value, labels) else: return value def render_list(lst, labels): items = [ '<li>%s</li>' % render_value(value, labels) for value in lst ] return '\n'.join(['\n<ul>'] + items + ['</ul>\n']) def render_dict(dct, labels): items = [] for key, value in dct.items(): if not value: continue key = labels.get(key, key) value = render_value(value, labels) items.append('<li><b>%s</b>: %s</li>' % (key, value)) return '\n'.join(['\n<ul>'] + items + ['</ul>\n']) 
0
source share

All Articles