Python constructs a custom method to beautify the dictionary structure output example, python dictionary

Source: Internet
Author: User

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)

Related Article

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.