![](/img/trans.png)
[英]Get key from dictionary by values and keys from nested dictionary in Python
[英]Retrieve all nested values from a key and sub keys till there is no key in python dictionary
我有一本包含以下元素的字典:
dict_Test={
'TEST':{'O','Z'},
'X':{'A','B','C'},
'T':{'tit'},
'C':{'D','E','F','TEST'},
'F':{'T'}
}
我試圖遍歷這本字典以最終獲得沒有重復元素的根元素,例如: find('x') 將返回 {A,B,D,E,tit,O,Z} 沒有元素有一個子元素。 我希望它足夠清楚,這是我試圖做到這一點的代碼
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))
我的問題是循環將在第 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}
例如這里它不會顯示“測試”的子元素我不確定我做錯了什么以及如何處理循環
謝謝:)
這個小代碼不能解決問題嗎?
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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.