gpt4 book ai didi

python - Python 中的嵌套字典迭代

转载 作者:行者123 更新时间:2023-12-01 05:08:55 26 4
gpt4 key购买 nike

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

在 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

但我不确定如何迭代嵌套字典并仍然保留整个对象。

最佳答案

您可以使用instanceof()方法来检查某个东西是否是一个字典,如果是的话,您可以让您的代码迭代这个字典。在这种情况下我会进行递归。

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)

关于python - Python 中的嵌套字典迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24564284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com