Okay I did some reading and should now rephrase my question:
I have restructured my josn to a tree like dict:
[{
"id": "Bosniak",
"system":
{
"0": "Wurde ein Nieren Protokoll gemacht, ist <25% der Lesion KM aufnehmend, und ist kein Fettgewebe zu sehenn(1) alles trifft zu?n(2) trifft nicht zu",
"1": {"0": "KM-aufnehmende Lesion >3cm, heterogene Lesion, viel Verkalkung?n(1) mind. eins davon trifft zun(2) trifft nicht zu",
"1":"Bosniak1", "2":"Bosniak II"},
"2": {"0": "Was ist zu sehen?n(1) >25% KM-aufnehmend oder fettign(2) homogene Lesion 20 - 30 HU",
"1": "Bosniak IV", "2":"Bosnaik V"}
}
}]
In a prior step I call an id in my dict, like "Bosniak" in this example. Now I want to iterate through the "system" key, Q&A-like via inputs through my console, until I have reached the end of a list (i.e. "Bosniak II")
I have this loop:
i = "1" #that is the index for the item with id "Bosniak" in my dict
while True:
qloop = input("Select an option: ", )
#probably here I need a recursive function
#or whatever where I can dynamically change my path,
# so that I can call items in my json dict until the
#end of a nested layer is reached
if #here I have some other code, not important
else:
print(data[i]["system"][qloop]["0"])
#if I type "1" it prints "KM-aufnehmende Lesion >3cm, heterogene Lesion, viel Verkalkung?n(1) mind. eins davon trifft zun(2) trifft nicht zu"
break
The expected output is being asked by my console "Select an option: ", iterating through my tree like dict based on my inputs, until there is no sublayer left, where it would finally print i.e. "Bosniak II"
2
Answers
When I try to run the program, it is throwing me an error
NameError: name 'i' is not defined. Did you mean: 'id'?
instead of an infinite loop. And after fixing the above error, getting the errorKeyError: '2'
, which is because of the key2
insideChoice 1
andChoice 2
ofsystem
. Made some tweaks to the existing code so that it will run successfully but it would be great if the exact goal or use case is provided. Note: As per the tweaks, Updated key2
to'2'
data variable dict and added vari
so that it can be incremented.if you give the input as
choice 1+3
, it would fail because we’re not fetching values of onlysystem
from the for loop.You can try this code snippet using a function:
If you want to iterate the entire data you can then use a while loop:
Replace the last two lines of code in the above snippet with: