Let's say I've got a nested dictionary of the form:
(假设我有以下形式的嵌套字典:)
{'geo': {'bgcolor': 'white','lakecolor': 'white','caxis': {'gridcolor': 'white', 'linecolor': 'white',}},
'title': {'x': 0.05},
'yaxis': {'automargin': True,'linecolor': 'white','zerolinecolor': 'white','zerolinewidth': 2}
}
How can you work your way through that dict and make a list of each complete key path that contains the value 'white'
?
(如何处理该字典,并列出包含值'white'
的每个完整键路径的列表?)
Using a function defined by user jfs in the post Search for a value in a nested dictionary python lets you check whether or not 'white'
occurs at least one time and also returns the path: (使用帖子中的用户jfs定义的功能在嵌套字典python中搜索值可让您检查'white'
是否至少发生了一次并返回了路径:)
# dictionary
d={'geo': {'bgcolor': 'white','lakecolor': 'white','caxis': {'gridcolor': 'white', 'linecolor': 'white',}},
'title': {'x': 0.05},
'yaxis': {'automargin': True,'linecolor': 'white','ticks': '','zerolinecolor': 'white','zerolinewidth': 2}
}
# function:
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
getpath(d,'white')
# out:
('geo', 'bgcolor')
But 'white' occurs other places too, like in :
(但是“白色”也发生在其他地方,例如:)
1. d['geo']['lakecolor']
(1. d['geo']['lakecolor']
)
2: d['geo']['caxis']['gridcolor']
(2: d['geo']['caxis']['gridcolor']
)
3: d['yaxis']['linecolor']
(3: d['yaxis']['linecolor']
)
How can I make sure that the function finds all paths?
(我如何确保该功能找到所有路径?)
I've tried applying the function above until it returns none
while eliminating found paths one by one, but that quickly turned into an ugly mess.
(我尝试应用上面的函数,直到它none
同时一一消除找到的路径,但是很快就变成了一个丑陋的混乱局面。)
Thank you for any suggestions!
(感谢您的任何建议!)
ask by vestland translate from so