[英]Nested Dictionary Iteration in Python
我有一本字典,其中包含一些選項鍵值對,然后是一個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()方法檢查某物是否為字典,如果為true,則可以使您的代碼遍歷該字典。 在這種情況下,我將進行遞歸。
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)
這是遞歸地遍歷字典結構的示例代碼。 對於此示例,它將描述替換為大寫描述。
_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)
PS您發布的示例數據不是有效的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": {}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.