![](/img/trans.png)
[英]How to read from a txt file into a dictionary where the value is a nested dictionary and the key of the nested dictionary is given by me?
[英]how to read dictionary key and values from a nested list and dictionary
我有嵌套字典和列表的以下字典,試圖輸出所有鍵“名稱”的值。 我不知道要在這本字典上實現的邏輯
期望輸出像
test
inside_test
inner_group1
GetFTP
字典數據:
{
"id": "0ce8df69-016b-1000-ffff-ffffbe50cb53",
"name": "test",
"processGroupStatusSnapshot": {
"name": "test",
"connectionStatusSnapshots": [],
"processorStatusSnapshots": [],
"processGroupStatusSnapshots": [
{
"id": "0ce90089-016b-1000-ffff-ffffadb84af5",
"processGroupStatusSnapshot": {
"name": "inside_test",
"connectionStatusSnapshots": [],
"processorStatusSnapshots": [],
"processGroupStatusSnapshots": [
{
"id": "0ce97287-016b-1000-0000-000056414ae7",
"processGroupStatusSnapshot": {
"id": "0ce97287-016b-1000-0000-000056414ae7",
"name": "inner_group1",
"connectionStatusSnapshots": [],
"processorStatusSnapshots": [
{
"id": "0ce9ca47-016b-1000-0000-0000496a342d",
"processorStatusSnapshot": {
"id": "0ce9ca47-016b-1000-0000-0000496a342d",
"groupId": "0ce97287-016b-1000-0000-000056414ae7",
"name": "GetFTP"
}
}
],
"processGroupStatusSnapshots": [],
"remoteProcessGroupStatusSnapshots": [],
"inputPortStatusSnapshots": [],
"outputPortStatusSnapshots": []
}
}
]
}
}
]
}
}
考慮到嵌套,以及鍵名在所有級別上都將保持不變的事實,我認為遞歸解決方案將在此處最有效。 請隨時使用此解決方案作為參考,並根據需要進行修改。
參數d
是這里的字典。
def find_name(d):
if 'processGroupStatusSnapshot' in d:
print("Name =", d['processGroupStatusSnapshot']['name'])
nxt = d['processGroupStatusSnapshot']['processGroupStatusSnapshots']
if len(nxt) > 0:
find_name(nxt[0])
find_name(d)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.