Python constructs a custom method to beautify the dictionary structure output example, python dictionary
Example:
Copy codeThe Code is as follows:
D = {"root": {"folder2": {"item2": None, "item1": None}, "folder1": {"subfolder1": {"item2 ": none, "item1": None}, "subfolder2": {"item3": None }}}}
Beautiful output:
Observe the following features:
1. the keys of the same level are left aligned, that is, the indent is the same.
2. line feed after.
3. If the value is a dictionary, that is, a nested dictionary is located at the next level, and the indent of each level key is different.
Train of Thought Analysis:
This is a "concatenation string" problem. The elements include "" {}:, \ n and space indent.
Traverse Key-value pairs (k, v) one by one and splice them into yield. When nested dictionaries are encountered, recursive + yield is used.
On the code.
# Coding = UTF-8 def pretty_dict (obj, indent = ''): def _ pretty (obj, indent): for I, tup in enumerate (obj. items (): k, v = tup # if it is a string, splice it with "" if isinstance (k, basestring ): k = '"% s"' % k if isinstance (v, basestring): v = '"% s"' % v # recursion if isinstance (v, dict): v = ''. join (_ pretty (v, indent + ''' * len (str (k) + ': {') # Calculate the indent of the next layer # case, according to (k, v) determine the position at which the stitching starts with if I = 0: #, and splice the left curly braces if len (obj) = 1: yield '{% s: % s} '% (k, v) else: yield' {% s: % s, \ n' % (k, v) elif I = len (obj) -1: # End, right curly braces yield '% s: % s}' % (indent, k, v) else: # intermediate yield '% 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)