Python 3.6+ btw
在嵌套字典中,如果子值与字符串匹配,我希望打印父值。为此,我尝试了这个递归调用。
for child in traverse_dict(value, 'ready', 'y'):
print(child)
也就是说,当找到父键时,我想(递归地)检查它的任何子值(和子键)是否匹配相应的字符串模式,如果是,打印。(我最终会收集这些值)
使用相同的调用,但函数外部按预期工作(尝试最后2行示例代码或如下所示)。
for i in traverse_dict(ex, 'ready', 'y'):
print(i)
# Output is
# Y
但当我尝试
for i in traverse_dict(ex, 'id'):
print(i)
# Output is
# checkpoint
# A
# checkpoint
# B
但我想
# Output is
# checkpoint
# Y <= (missing this, output of traverse_dict(ex, 'ready', 'y'))
# A
# checkpoint
# B
知道为什么在函数内部调用时会失败吗?
参见此示例
ex = [
{
'Id': 'A',
'Status': { 'Ready': 'Y' }
},
{
'Id': 'B',
'Status': { 'Ready': 'N' }
}
]
def traverse_dict(
data,
*args
):
if isinstance(data, dict):
for key, value in data.items():
# FOR SUB-GENERATOR WHERE *ARGS IS PASSED 2 ARGS
try:
if key.lower() == args[0] and value.lower() == args[1]:
yield value
else:
yield from traverse_dict(value, *args)
except:
if key.lower() == args[0]:
print('checkpoint')
for child in traverse_dict(value, 'ready', 'y'):
print(child)
yield value
else:
yield from traverse_dict(value, *args)
elif isinstance(data, list):
for item in data:
yield from traverse_dict(item, *args)
for i in traverse_dict(ex, 'id'):
print(i)
for i in traverse_dict(ex, 'ready', 'y'):
print(i)
提前感谢!
发布于 2020-07-03 07:05:38
您在for child in traverse_dict(value, 'ready', 'y'):...
行中传递了错误的数据。在您的示例中,value
包含"A“,因为当键为Id
而值为A
或B
时,key.lower() == args[0]
语句为True
。您应该传递当前dict的'Status'
成员。
它的意思是正确的行:for child in traverse_dict(data['Status'], 'ready', 'y'):
这一行的输出:
>>> python3 test.py
checkpoint
Y
A
checkpoint
B
Y
https://stackoverflow.com/questions/62716911
复制相似问题