This article mainly introduces how to construct a custom method using Python to beautify the output of the dictionary structure. The principle is to concatenate strings using recursive methods. For more information, see
Example:
The code is as follows:
d = { "root": { "folder2": { "item2": None, "item1": None }, "folder1": { "subfolder1": { "item2": None, "item1": None }, "subfolder2": { "item3": None } } } }
Beautiful output:
# 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)
For more articles about how to create custom methods in Python to beautify the dictionary structure output, refer to the PHP Chinese website!