[英]Recursively searching through dictionary returning complete hirerachy
我的問題陳述是我有搜索查詢,我必須返回與查詢匹配的字典,以維護層次結構。
我能夠做到第一。 但是我想從一開始就返回完整的層次結構,如下所示
獲取此輸出:
{"Name":"google search","items":[],"properties":{"id":1,"process":123}
預期產量:
{
"items":[
{'Name':'chrome','items':
[
{"Name":"google search","items":[],"properties":{"id":1,"process":123}}
]
},
]
}
這是我的示例輸入:
myinput = {
"items":[
{'Name':'firefox','items':[],"properties":{"one":1,"two":2}},
{'Name':'chrome','items':[
{'Name':"stackoverflow","items":[],"properties":{"one":1,"two":2}},
{"Name":"google search","items":[],"properties":{"id":1,"process":123}}
],
"properties":{"one":1,"two":2}},
{'Name':'new','items':[],"properties":{"one":1,"two":2}},
{'Name':'new','items':[],"properties":{"one":1,"two":2}},
]
}
這是我迄今為止嘗試過的
matched_items = []
def resursive_fun(Nodes, searchQuery):
for key, value in Nodes.iteritems():
if isinstance(value, list):
for item in value:
matchValue = match_items(searchQuery, item['properties'])
if matchValue:
matched_items.append(item)
resursive_fun(item, searchQuery)
return matched_items
searchDict = {"id": 1, "process": 123}
resursive_fun(myinput, searchDict)
我認為您需要從任何成功的遞歸調用的返回值中構建返回值,而不是使用全局列表(如果您需要進行多次搜索,這將導致各種問題)。 如果沒有匹配項,則應返回具有特殊含義的內容(如None
)。
嘗試這樣的事情:
def recursive_search(data, query):
if match_items(searchQuery, data["properties"]): # base case
return data
if "items" in data and isinstance(data["items"], list): # recursive case
for item in data["items"]:
x = recursive_search(item, query)
if x is not None: # recursive search was successful!
return {"Name": data["Name"], "items": [x]}
return None # if search is not successful, return None
return None
可以省略,因為None
是不返回其他任何值的函數的默認返回值。 但是,我認為最好在“ None
具有某些含義時要明確一些,就像在這里一樣。
如果您不僅要查找第一個匹配結果,而且要查找所有匹配結果,則需要用一些更細微的行為來替換早期return
調用,這些行為只有在某處找到匹配項時才返回值:
def recursive_search(data, query):
result = {}
if if "properties" in data and match_items(searchQuery, data["properties"]):
result["properties"] = data["properties"]
if "items" in data and isinstance(data["items"], list):
for item in data["items"]:
result_items = []
x = recursive_search(item, query)
if x is not None:
result_items.append(x)
if result_items: # recursive search found at least one match
result["items"] = result_items
if result: # some part of the search found a match (either here or deeper)
if "Name" in data:
result["Name"] = data["Name"]
return result
else:
return None
您也可以在失敗的匹配中返回一個空字典,而不是None
。 為此,將if result: if "Name" in data:
行更改為單行if result and "Name" in data:
if result: if "Name" in data:
行的末尾,並無條件地執行return result
(取消縮進並刪除else: return None
)。 將遞歸情況下的if x is not None
更改為if x
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.