Python constructs custom methods to beautify dictionary structure output

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.