### 在嵌套Dict中递归查找路径

``````d = {
"@timestamp": "2019-01-08T19:33:50.066Z",
"metricset": {
"rtt": 2592,
"name": "filesystem",
"module": "system"
},
"system": {
"filesystem": {
"free_files": 9660022,
"type": "rootfs",
"device_name": "rootfs",
"available": 13555355648,
"files": 9766912,
"mount_point": "/",
"total": 19992150016,
"used": {
"pct": 0.322,
"bytes": 6436794368
},
"free": 13555355648
}
},
"host": {
"name": "AA"
},
"beat": {
"name": "AA",
"hostname": "AA",
"version": "6.3.2"
}
}
``````

``````system.filesystem.type
``````

``````def traverse(valuelist, dictionary):

for k,v in dictionary.items():

if isinstance(v, dict):
traverse(valuelist,v)
else:
valuelist.append(v)

return valuelist
``````

``````def getpath(nested_dict, value, prepath=()):
for k,v in nested_dict.items():
path = prepath + (k,)
if v == value: # found value
return path
elif hasattr(v, 'items'): # v is a dict
p = getpath(v, value, path) # recursive call
if p is not None:
return p
``````

#### 1 个答案:

``````def getpath(nested_dict, value, prepath=()):
for k,v in nested_dict.items():
path = prepath + (k,)
if v == value: # found value
yield path # yield the value
elif hasattr(v, 'items'):
yield from getpath(v, value, path) # yield all paths from recursive call
``````

``````for path in getpath(nested_dict, value):
# do stuff with path
``````