Python中的嵌套字典迭代

时间:2014-07-03 22:37:01

标签: python dictionary

我有一个字典,它有一些选项键值对,然后是一个sub_dict属性,它是一个具有相同属性的更多字典的列表,这些也有可能让sub_dicts一直向下。

在python中,我将它分开并单独处理它们并一次更改它们,并希望将已更改的系统与整个系统重新组合。我不知道如何迭代它。

{base_system: {
name: "root",
description: "data dictionary",
common_data: {},
other_data: {},
more_data: {},
sub_systems: [
    {
        base_system: {
        name: "another system",
        description: "inherits from top level",
        sub_systems: [
            {
                base_system: {}
            },
            {
                base_system: {}
            }
        ]
        }
    },
    {
        base_system: {
            name: "one more system",
            description: "inheriting again",
            sub_systems: [
            {
                base_system: {
                name: "child system",
                description: "no kids here",
                other_data: {},
                more_data: {}
                }
            },
            {
                base_system: {
                name: "kid system",
                description: "no children here"
                }
            }
            ]
        }
    }
]
}

}

我想做这样的事情,但我不知道如何做到递归。

#Have some recursive function to dig through the overall dictionary then test:
if the_dict_object["space_system"]["name"] == changed_json_system["space_system"]["name"]:
  #then when it passes that if statement I can just set
  the_dict_object = changed_json_system

但是我不知道如何遍历嵌套字典并仍然掌握整个对象。

2 个答案:

答案 0 :(得分:1)

您可以使用instanceof()方法检查某些内容是否为dict,然后如果为true,则可以使您的代码遍历此dict。在这种情况下我会做一个递归。

def read_dict(some_dictionary):
    for key, value in some_dictionary:

        if isinstance(value, dict): 
            # if value is another dict, iterate through the key,value pairs in value
            read_dict(value) 
        elif isinstance(value, list):
            # if value is a list, add your own code to iterate through a list
            pass
        else:
            #not a dict, do what you needed to do eg:
            print 'value of %s is %s' % (key, value) 

read_dict(the_dict_object)

答案 1 :(得分:1)

以下是递归遍历dict结构的示例代码。对于此示例,它将描述替换为描述的大写。

_DESC = "description"
_BASESYS = "base_system"
_SUBSYS = "sub_systems"

def uppercase_desc(system_info):
    """
    Change a system object such that the description is in upper-case.
    """
    if _BASESYS not in system_info:
        return

    subd = system_info[_BASESYS]
    if _DESC in subd:
        subd[_DESC] = subd[_DESC].upper()
    if _SUBSYS not in subd:
        return
    for d in subd[_SUBSYS]:
        uppercase_desc(d)

if __name__ == "__main__":
    import json
    with open("data.json", "rt") as f:
        s = f.read()
    system_info = json.loads(s)

    uppercase_desc(system_info)
    s = json.dumps(system_info, indent=4, sort_keys=True)
    print(s)

上面的代码就地修改了字典。在你去的时候制作副本然后返回副本会有点棘手,但并不坏。这可能是更可取的。

这里唯一棘手的部分是代码默认使用copy.deepcopy()。由于我们不知道字典中可能包含的内容,并且我们想要返回副本,因此我们可以在所有内容上调用copy.deepcopy();它将在3(值为3的整数对象)等简单对象上轻松工作并做正确的事。

import copy

_DESC = "description"
_BASESYS = "base_system"
_SUBSYS = "sub_systems"

def uppercase_desc(system_info):
    """
    Change a system object such that the description is in upper-case.
    """
    if _BASESYS not in system_info:
        raise ValueError("only works on a system info dict")

    # put in the base_system key and an empty subdir
    newsubd = {}
    new_system_info = {_BASESYS: newsubd}

    subd = system_info[_BASESYS]
    for key, value in subd.items():
        if _DESC == key:
            newsubd[key] = value.upper()
        elif _SUBSYS == key:
            newsubd[key] = [uppercase_desc(d) for d in value]
        else:
            newsubd[key] = copy.deepcopy(value)
    return new_system_info

if __name__ == "__main__":
    import json
    with open("data.json", "rt") as f:
        s = f.read()
    system_info = json.loads(s)

    new_system_info = uppercase_desc(system_info)
    s = json.dumps(new_system_info, indent=4, sort_keys=True)
    print(s)

P.S。您发布的示例数据不是有效的JSON。我通过在键周围加上双引号来修改它,并用漂亮的缩进打印它,以制作我的测试文件data.json。这是:

{
    "base_system": {
        "name": "root", 
        "description": "data dictionary", 
        "more_data": {}, 
        "common_data": {}, 
        "sub_systems": [
            {
                "base_system": {
                    "name": "another system", 
                    "sub_systems": [
                        {
                            "base_system": {}
                        }, 
                        {
                            "base_system": {}
                        }
                    ], 
                    "description": "inherits from top level"
                }
            }, 
            {
                "base_system": {
                    "name": "one more system", 
                    "sub_systems": [
                        {
                            "base_system": {
                                "more_data": {}, 
                                "other_data": {}, 
                                "name": "child system", 
                                "description": "no kids here"
                            }
                        }, 
                        {
                            "base_system": {
                                "name": "kid system", 
                                "description": "no children here"
                            }
                        }
                    ], 
                    "description": "inheriting again"
                }
            }
        ], 
        "other_data": {}
    }
}