Demo Sample:
D = {"root": {"Folder2": {"item2": None, "Item1": none}, "Folder1": {"Subfolder1": {"item2": None, "Item1": none}, "Subfolder2": {"Item3": None}}}
The beautiful output is:
Observe the features:
1. Key to the same level is left aligned, i.e. indent is also
2. Change the line after the number
3. Assume that value is a dictionary. Nested dictionaries, the nested dictionaries are at the next level, and the indent of each level key are different
Thinking Analysis:
This is a "stitching string" problem with the element "" "{}:,\n and Space indent.
Traverse each (k, v) key value pairs, splicing yield up, encounter nested dictionary recursive
Recursive +yield
On the code.
#coding =utf-8def pretty_dict (obj, indent= "): Def _pretty (obj, indent): For I, tup in Enumerate (Obj.items ()): K, v = tup #假设是字符串则拼上 "" If Isinstance (K, basestring): k = '%s ' '% K if Isinstan Ce (V, basestring): v = '%s ' '% v #假设是字典则递归 if isinstance (V, dict): v = '. Join (_prett Y (V, indent + ' * len (str (k) + ': {'))) #计算下一层的indent #case, according to (K,V) to where to determine where to splice what if I = = 0: #开头, to spell the left curly brace If Len (obj) = = 1:yield ' {%s:%s} '% (k, v) else:yield ' {%s:%s,\n '% (k, v) elif i = = Len (obj)-1: #结尾, spell right curly brace yield '%s%s:%s} '% (indent, K, v) else: #中间 yield '%s%s:%s,\n '% (indent, K, v) print '. Join (_pretty (obj, indent)) d = {"root": {"fol Der2 ": {" item2 ": None," Item1 ": none}," Folder1 ": {" Subfolder1 ": {" item2 ": None," Item1 ": none}," Subfolder2 ": {" ite M3 ": None}}}}pretty_Dict (d)
Elegant Python-implements a pretty function beautiful output nested dictionary