在Python字典中记录键路径的递归函数


下午好。

我希望有人能帮助我这个函数我试图定义,我看了看已经问过类似的问题,但不幸的是,这对我来说仍然不清楚。

我的目标是递归地遍历一个嵌套字典,并记录到达每个最终键所需的键径。

所以如果我有这样的dic例如:

example_dic = {
"fruitType": 'apple',
"orderNumber": 12345,
"links": {
"self": {
"href": 'https://foo'
}
},
"customerName": 'bob'
}

期望的输出(现在我只是打印)将是类似

的东西
fruitType
orderNumber
links self href
customerName

这是我到目前为止所完成的:

def get_key_path(to_find_keys, key_path):
for key in to_find_keys.keys():
print key
key_path.append(key) # Append to list
try:
get_key_path(to_find_keys[key], key_path) # About to call function recursively 
except AttributeError:
print key_path # Found last key, print it.
key_path = []  # Reset list

现在它确实成功地找到了dic中的最后一个键,但是我在重置列表时遇到了麻烦。如果我的dic有很多条目和嵌套,列表会在错误的时刻重置。

我还在学习Python(和一般的编程),所以可能有一个关于递归的基本元素我遗漏了。

提前感谢任何可以帮助的人!

您可以使它成为递归生成器。遍历字典中的键和值,并递归查找字典中的值。仅为非字典的值提供键。

def keyPaths(d):
for k,sd in d.items():
if isinstance(sd,dict):
yield from (f"{k} {sub}" for sub in keyPaths(sd))
else:
yield k

输出:

example_dic = {
"fruitType": 'apple',
"orderNumber": 12345,
"links": {
"self": {
"href": 'https://foo'
}
},
"customerName": 'bob'
}
for path in keyPaths(example_dic):
print(path)
fruitType
orderNumber
links self href
customerName

最新更新