Python 3.6+btw
从嵌套字典中,如果子值与字符串匹配,我想打印父值。为此,我尝试了这个递归调用
for child in traverse_dict(value, 'ready', 'y'):
print(child)
也就是说,当找到父键时,我想(递归地)检查它的任何子值(和子键)是否与相应的字符串模式匹配,如果是,则打印。(我最终会收集这些值)
使用相同的调用,但不在函数范围内,可以按预期工作(请尝试最后两行示例代码或参见下文)
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)
提前谢谢
您在
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'):
此行的输出:
相关问题 更多 >
编程相关推荐