Python constructs custom methods to beautify dictionary structure output

高洛峰
Release: 2018-05-29 10:33:58
Original
2404 people have browsed it

Example:

The code is as follows:

d = { "root": { "folder2": { "item2": None, "item1": None }, "folder1": { "subfolder1": { "item2": None, "item1": None }, "subfolder2": { "item3": None } } } }
Copy after login

The beautiful output is:

Python constructs custom methods to beautify dictionary structure output

##Observe the characteristics:

1. The keys of the same level are left aligned, that is, the indent is the same.

d = { "root": { "folder2": { "item2": None, "item1": None }, "folder1": { "subfolder1": { "item2": None, "item1": None }, "subfolder2": { "item3": None } } } }
Copy after login

2. Break the line after the number.

3. If value is a dictionary, that is, a nested dictionary, then the nested dictionary is at the next level, and the indent of the key at each level is different.

Idea analysis:

This is a "splicing string" problem. The elements include ""{}:,\n and space indent.
Traverse each (k, v) key-value pair, splice them together for yield, and recurse when encountering a nested dictionary, that is, recursion + yield.

Upload 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 isinstance(k, basestring): k = '"%s"'% k 
   if isinstance(v, basestring): v = '"%s"'% v 
   #如果是字典则递归 
   if isinstance(v, dict): 
    v = ''.join(_pretty(v, indent + ' '* len(str(k) + ': {')))#计算下一层的indent 
   #case,根据(k,v)对在哪个位置确定拼接什么 
   if i == 0:#开头,拼左花括号 
    if len(obj) == 1: 
     yield '{%s: %s}'% (k, v) 
    else: 
     yield '{%s: %s,\n'% (k, v) 
   elif i == len(obj) - 1:#结尾,拼右花括号 
    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)
Copy after login
For more Python construction custom methods to beautify dictionary structure output related articles, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!