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

Python 如何创建递归函数将多级字典对象打印到文件,python,dictionary,recursion,Python,Dictionary,Recursion,我需要一个函数以稍微格式化的文本方式将字典打印到文件中。字典可以在任何级别包含更多字典、列表、布尔值和字符串(简单属性)。因此,我试图创建一个函数,可以递归地适当地处理每个项。一旦我将内容作为字符串获取,我就可以将其写入文件 格式约束指定,对于嵌套字典对象,属性名称将成为标题/标题。当我们进入嵌套级别时,我们可能需要添加选项卡以提高可见性 例如,下面是一个字典结构示例,以及输出的外观: 我的输入如下: { 'service': { 'license': 'xxx-yyy-zzz' },

我需要一个函数以稍微格式化的文本方式将字典打印到文件中。字典可以在任何级别包含更多字典、列表、布尔值和字符串(简单属性)。因此,我试图创建一个函数,可以递归地适当地处理每个项。一旦我将内容作为字符串获取,我就可以将其写入文件

格式约束指定,对于嵌套字典对象,属性名称将成为标题/标题。当我们进入嵌套级别时,我们可能需要添加选项卡以提高可见性

例如,下面是一个字典结构示例,以及输出的外观:

我的输入如下:

{
'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
------------ 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
}

我的输出如下:

{
'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
------------ 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
我尝试过的

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

有人能帮我找到确切的函数吗?

您可以将递归与生成器结合使用:

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)))
输出:

------------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

感谢您的回复,我得到了以下语法错误:
yield“\t”*(1级)+f'{a}={b}
->SyntaxError:invalid syntax[runtime is python 3.5]@radeepath是的,我发布的原始代码使用了
f-string
s,这些代码仅在>=python 3.6版本中可用。请参阅我最近的编辑,因为我更新了解决方案以与您当前的版本兼容。谢谢@Ajax1234。这正是我要找的。我解决了一个小问题。我将与大家分享:将=>
用于d.items()中的a,b:
更改为
如果isinstance(d,str):产生“\t”*(1级)+“{}”。格式(d)其他:用于d.items()中的a,b:
否则它被字符串数组阻塞。如果可能的话,请添加一些代码的简要说明。这将有助于学习。