回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我试图从字典中获取所有的key、val对,我的目标是当key-value对与某个值匹配时从函数返回true,如果没有匹配则返回false。我观察到在递归调用中使用“return”时,“for”循环会导航到最内层的循环,但会在那里停止,并且不会执行其余的外层循环。不知道为什么?根据递归的概念,它们应该。我错过了什么</p>
<p>下面是代码片段</p>
<pre><code>resp = ' { "name": "Stuart", "response" : { "age" : "27", "weight" : "50"}, "address" : "New York" }'
response = json.loads(resp)
def recursive_loop(response):
for key, value in response.items():
if type(value) is dict:
return recursive_loop(value)
elif key == "address" and value == "New York":
print ("Match")
return True
else:
print (value)
return False
z = recursive_loop(response)
print (z)
</code></pre>
<p>我得到的输出:</p>
<pre><code>Stuart
27
50
False
</code></pre>
<p>我期望的结果是:</p>
<pre><code>Stuart
27
50
Match
True
</code></pre>