Example:
The code is as follows:
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 the same.
D = {"root": {"Folder2": {"item2": None, "Item1": none}, "Folder1": {"Subfolder1": {"item2": None, "Item1": none}, "Subfolder2": {"Item3": None}}}
2. Change the line after the number.
3. If value is a dictionary, which is a nested dictionary, the nested dictionary is at the next level, and the indent of each level key is different.
Thinking Analysis:
This is a "stitching string" problem with the element "" "{}:,\n and Space indent.
Traverse A (k, V) key value pairs, splicing yield up, encounter nested dictionary recursive, that is, recursive +yield.
On the code.
#coding =utf-8 def pretty_dict (obj, indent= "): Def _pretty (obj, indent): For I, tup in Enumerat E (Obj.items ()): K, v = tup #如果是字符串则拼上 "" If Isinstance (K, basestring): k = '%s ' '% K if isinstance (V, Basestrin g): v = '%s ' '% v #如果是字典则递归 if isinstance (V, dict): v = '. Join (_pretty (V, indent + ' * len (str (k) + ': {')) #计 Calculate the next layer of the indent #case, according to (K,V) in which position to determine the stitching what if i = = 0: #开头, the left curly brace if len (obj) = = 1:yield ' {%s:%s} '% (k, v) El Se: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": {"Folder2": {"item2": None, "Item1": none}, "Folder1": {"Subfolder1": {"item2": None, "Item1": none}, "Subfolder2": {"Item3": None}}} Pretty _dict (d)