Python constructs a custom method to beautify the dictionary structure output

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

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.