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

标签 python dictionary recursion

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

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

例如,这里是字典结构的示例以及输出的样子:

我的输入是这样的:

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

关于python - 如何创建递归函数将多级字典对象打印到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59219732/

相关文章:

swift - 如何从 swift 字典中删除键值对?

java - 给定一串字符时查找所有有效单词(递归/二进制搜索)

python - 如何在 PyQt5 中设置 PlotWidget 刻度颜色?

python - 等待元素使用 CSS 选择器加载标识元素

c++ - 类型删除映射的拷贝(分配)应该有多深

c++ - 套接字和映射的内存泄漏

python - 如何从 Django 中的查询集中检索值?

python - Seaborn 错误?热图绘制不一致

python - 内存无法按预期工作

c++ - 二叉搜索树插入中迭代和递归的区别