迭代python中的嵌套对象

时间:2017-07-18 20:48:17

标签: python

我有一个看起来像这样的python对象。我正在尝试解析此对象并将其转换为人类可读的字符串,我需要将其放入日志中。考虑到对象可以是嵌套字典或嵌套列表或词典中的列表内的字典等,我如何递归循环呢?

// your code
<?php
    for($page=1;$page<=$number_of_pages;$page++)
    {
        echo "<a id='pagingLink' href='adminControl.php?page=" . $page . "&valueToSearch=". urlencode($_GET['valueToSearch']) ."&search'>" . $page . "</a>";
    }
?>
// your code

我想序列化上面的内容看起来像这样

{"plugins": 
  [
    {"Chrome PDF Viewer": "mhjfbmdgcfjbbpaeojofohoefgiehjai"}, 
    {"Chrome PDF Viewer": "internal-pdf-viewer"}, 
    {"Native Client": "internal-nacl-plugin"}, 
    {"Shockwave Flash": "PepperFlashPlayer.plugin"}, 
    {"Widevine Content Decryption Module": "widevinecdmadapter.plugin"}
  ]
}

到目前为止我的代码[这适用于嵌套字典,但我不知道如何更改它以支持上述对象中的列表]:

"plugins: 
     Chrome PDF Viewer": "mhjfbmdgcfjbbpaeojofohoefgiehjai, 
     Chrome PDF Viewer": "internal-pdf-viewer, 
     Native Client": "internal-nacl-plugin, 
     Shockwave Flash": "PepperFlashPlayer.plugin, 
     Widevine Content Decryption Module": "widevinecdmadapter.plugin"

我已经查看了可能的答案,但找不到解决方案。

3 个答案:

答案 0 :(得分:2)

也许pformat的输出适合你:

from pprint import pformat
results_str = pformat(results)

答案 1 :(得分:2)

格式化可能有点偏离

def humanizer(input, result=''):
    if type(input) == dict:
        for k, v in input.items():
            if type(v) == str:
                result += '%s:%s\n\t' % (str(k), str(v))
            elif type(v) in (dict, list):
                result += '%s:\n\t' % str(k)
                result = humanizer(v, result)
                result += '\n\t'
    elif type(input) == list:
        for item in input:
            if type(item) == str:
                result += item
                continue
            result = humanizer(item, result) + '\n\t'
    else:
        result += input + '\n\t'
    return result

结果:

plugins:
        Chrome PDF Viewer:mhjfbmdgcfjbbpaeojofohoefgiehjai

        Chrome PDF Viewer:internal-pdf-viewer

        Native Client:internal-nacl-plugin

        Shockwave Flash:PepperFlashPlayer.plugin

        Widevine Content Decryption Module:widevinecdmadapter.plugin

答案 2 :(得分:1)

如果是type == list和缩进跟踪器,则需要elif条件:

data = {"plugins": 
  [
    {"Chrome PDF Viewer": "mhjfbmdgcfjbbpaeojofohoefgiehjai"}, 
    {"Chrome PDF Viewer": "internal-pdf-viewer"}, 
    {"Native Client": "internal-nacl-plugin"}, 
    {"Shockwave Flash": "PepperFlashPlayer.plugin"}, 
    {"Widevine Content Decryption Module": "widevinecdmadapter.plugin"}
  ],
  "anotherLevel":
    {
        "sublevel": [
            {'item1': 'value1'}
        ]
    }
}

result_str = ""
def dictionary_iterator(indent, data):
    global result_str

    if isinstance(data, dict):
        for key, value in data.items():
            result_str += indent*'\t' + key + '\n'
            indent = indent + 1
            dictionary_iterator(indent, value)

    elif isinstance(data, list):
        for item in data:
            if isinstance(item, dict) and len(list(item.keys())) == 1:
                key = list(item.keys())[0]
                value = item[key]
                result_str += indent*'\t' + key + ': ' + value + '\n'
            else:
                indent = indent + 1
                dictionary_iterator(indent, item)
    return result_str


if __name__ == '__main__':
    print(dictionary_iterator(0, data))

那将打印出来:

plugins
    Chrome PDF Viewer: mhjfbmdgcfjbbpaeojofohoefgiehjai
    Chrome PDF Viewer: internal-pdf-viewer
    Native Client: internal-nacl-plugin
    Shockwave Flash: PepperFlashPlayer.plugin
    Widevine Content Decryption Module: widevinecdmadapter.plugin
    anotherLevel
        sublevel
            item1: value1