I have a dictionary with elements like this:
dict_Test={
'TEST':{'O','Z'},
'X':{'A','B','C'},
'T':{'tit'},
'C':{'D','E','F','TEST'},
'F':{'T'}
}
I was trying to loop through this dictionary to finally have the root elements with no duplicate element that already exist for example: find('x') would return {A,B,D,E,tit,O,Z} no element that has a sub element. I hope it is clear enough well here is my code in attempt to do that
def GetInputs( keyToRetrieve):
dict = [dict_Test]
while dict:
mapping = dict.pop()
try:
items = mapping.items()
except AttributeError:
continue
for key, value in items:
if key == keyToRetrieve:
return value
else:
dict.append(value)
dict_Test={
'TEST':{'O','Z'},
'X':{'A','B','C'},
'T':{'tit'},
'C':{'D','E','F','TEST'},
'F':{'T'}
}
inputs={}
i=1
for input in GetInputs('X'):
while True:
for inputValue in input:
input=GetInputs(inputValue)
print('[Itter '+str(i)+' ] RelatedInput: '+str(inputValue)+' value: '+str(input)+'__'+str(input==None))
i+=1
if input==None:
inputs.update({inputValue:input})
else :
input=list(GetInputs(inputValue))
if input==None:
break
print('Result: '+str(inputs))
My problem is that the loop will stop at level 2
[Itter 1 ] RelatedInput: B value: None__True
[Itter 2 ] RelatedInput: C value: {'D', 'E', 'TEST', 'F'}__False
[Itter 3 ] RelatedInput: D value: None__True
[Itter 4 ] RelatedInput: E value: None__True
[Itter 5 ] RelatedInput: TEST value: {'Z', 'O'}__False
[Itter 6 ] RelatedInput: F value: {'T'}__False
[Itter 7 ] RelatedInput: T value: {'tit'}__False
[Itter 8 ] RelatedInput: tit value: None__True
[Itter 9 ] RelatedInput: A value: None__True
Result: {'B': None, 'D': None, 'E': None, 'tit': None, 'A': None}
For example here it will not show sub element of 'Test' I m not sure what am I doing wrong and how could I possibly handle the loop
Thanx:)
Does this small code not solve the task?
def find(x):
res = []
for item in dict_Test[x]:
if item not in dict_Test:
res.append(item)
else:
res.extend(find(item))
return res
print(find('X')) # ['B', 'A', 'D', 'O', 'Z', 'tit', 'E']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.