Elegant Python-implements a pretty function beautiful output nested dictionary

Source: Internet
Author: User

Demo Sample:

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 also
2. Change the line after the number
3. Assume that value is a dictionary. Nested dictionaries, the nested dictionaries are at the next level, and the indent of each level key are different


Thinking Analysis:
This is a "stitching string" problem with the element "" "{}:,\n and Space indent.
Traverse each (k, v) key value pairs, splicing yield up, encounter nested dictionary recursive

Recursive +yield


On the code.

#coding =utf-8def pretty_dict (obj, indent= "): Def _pretty (obj, indent): For I, tup in Enumerate (Obj.items ()): K, v = tup #假设是字符串则拼上 "" If Isinstance (K, basestring): k = '%s ' '% K if Isinstan Ce (V, basestring): v = '%s ' '% v #假设是字典则递归 if isinstance (V, dict): v = '. Join (_prett                Y (V, indent + ' * len (str (k) + ': {'))) #计算下一层的indent #case, according to (K,V) to where to determine where to splice what if I = = 0: #开头, to spell the left curly brace  If Len (obj) = = 1:yield ' {%s:%s} '% (k, v) else: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": {"fol Der2 ": {" item2 ": None," Item1 ": none}," Folder1 ": {" Subfolder1 ": {" item2 ": None," Item1 ": none}," Subfolder2 ": {" ite M3 ": None}}}}pretty_Dict (d) 


Elegant Python-implements a pretty function beautiful output nested dictionary

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.