简体   繁体   English

如何创建递归函数以将多级字典对象打印到文件

[英]How to create a recursive function to print a multilevel dictionary object to a file

I need a function to print a dictionary to a file in a slightly formatted textual manner.我需要一个函数以稍微格式化的文本方式将字典打印到文件中。 The dictionary can contain more dictionaries, lists, boolean and string (simple properties) at any level.字典可以在任何级别包含更多字典、列表、布尔值和字符串(简单属性)。 So I am trying to make a function that can recursively process each item appropriately.所以我试图制作一个可以适当地递归处理每个项目的函数。 Once I get the content as a string i can write to a file.一旦我将内容作为字符串,我就可以写入文件。

Formatting constraints specify that for nested dictionary objects, the property name becomes the title/header.格式约束指定对于嵌套字典对象,属性名称成为标题/标题。 And as we move into nested levels we should possibly add tabs for visibility.当我们进入嵌套级别时,我们可能应该添加选项卡以提高可见性。

For example here is a sample of dictionary structure and how the output should look like:例如,这里是一个字典结构示例以及输出应该是怎样的:

My Input Is like this:我的输入是这样的:

{
'service': {
    'license': 'xxx-yyy-zzz'
},
'macros': {},
'apps': [{
    'app1': {
        'enabled': True,
        'property_token': 'abcd'
    },
    'app2': {
        'enabled': True,
        'db_configured': False,
        'db_pass': 'xyz',
    }}],
'files': {
    'log_files': [{
        'last_modified': 1571663356,
        'name': 'file1'
    }, {
        'last_modified': 1571663356,
        'name': 'file2'
    }]
},
'bool_property': False

} }

My Output Is like this:我的输出是这样的:

------------ SERVICE ------------------

license = xxx-yyy-zzz


------------ MACROS -----------------

NONE


------------ APPS -----------------

        ------ app1 ----

        enabled = True
        property_token = abcd

        ------ app2 ----

        enabled = True
        db_configured = False
        db_pass = xyz


------------ FILES -----------------


        ------ Log Files ----


            --------    
            name = file1
            last_modified = 1571663356
            --------
            name = file1
            last_modified = 1571663356

What i have tried我试过的

def print_o(self, obj, report):

        if isinstance(obj, dict):
            for key, v in obj.items():
                if isinstance(obj, str) == False:
                    report += "======" + key + "========>"
                    report += "=========================="
                    report += os.linesep
                    report += os.linesep
                    self.print_o(v, report)
                if isinstance(v, str) == False:
                        self.print_o(v, report)
                else:
                    report += key + " = " + str(v)
                    report += os.linesep

        elif isinstance(obj, list):
            for v in obj:
                if isinstance(v, str) == False:
                        self.print_o(v, report)
                else:
                    report += str(v)
                    report += os.linesep

        elif isinstance(obj, str):
                report += obj
                report += os.linesep

        else:
                report += "==================="
                report += os.linesep


        report += os.linesep

Can someone please guide me to the exact function that will help me?有人可以指导我了解对我有帮助的确切功能吗?

You can use recursion with a generator:您可以将递归与生成器一起使用:

def flatten(d, level = 0):
   for a, b in d.items():
     if not isinstance(b, (list, dict)):
        yield "\t"*(level-1)+'{}={}'.format(a, b)
     elif isinstance(b, dict):
        yield "\t"*(level)+'{}{}{}'.format("-"*12, a.upper(), "-"*12)
        yield from (['NONE'] if not b else flatten(b, level+1))
     else:
        yield "\t"*(level)+'{}{}{}'.format("-"*12, a.upper(), "-"*12)
        for i in b:
           yield from flatten(i, level+1)
           yield "\t"*(level)+'{}'.format("-"*12)

data = {'service': {'license': 'xxx-yyy-zzz'}, 'macros': {}, 'apps': [{'app1': {'enabled': True, 'property_token': 'abcd'}, 'app2': {'enabled': True, 'db_configured': False, 'db_pass': 'xyz'}}], 'files': {'log_files': [{'last_modified': 1571663356, 'name': 'file1'}, {'last_modified': 1571663356, 'name': 'file2'}]}, 'bool_property': False}
print('\n'.join(flatten(data)))

Output:输出:

------------SERVICE------------
license=xxx-yyy-zzz
------------MACROS------------
NONE
------------APPS------------
    ------------APP1------------
    enabled=True
    property_token=abcd
    ------------APP2------------
    enabled=True
    db_configured=False
    db_pass=xyz
------------FILES------------
    ------------LOG_FILES------------
    last_modified=1571663356
    name=file1
    ------------
    last_modified=1571663356
    name=file2
    ------------
bool_property=False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM