函数的返回值为 None 且无法返回第一个键



这里有一个看似简单的递归函数,它在字典中循环。我想打印我的值v,就像我已经在做的那样,我想返回与这个键相关的第一个键:值对。在这种情况下,代码输出v = 'hi'None。我不知道为什么它一直返回无。我将k变量设置为函数外的一个空字符串。在这种情况下,K应该是CCD_ 3。此外,我希望代码以某种方式返回'five',因为它是第一个键,但我不确定这是否可能。有人能帮忙吗?我也为钥匙的任何混乱提前道歉。在这里,代码应该返回k='six'。我不知道我将如何返回{'six': 'hi'}的密钥。

my_dict = {'one': {'two': 'hello'}, 'three': {'four': 'hey'}, 'five': {'six': 'hi'}}
k = ''
numero = 'six'
def find_location(d):
for k, v in d.iteritems():
if isinstance(v, dict):
find_location(v)
else:
if numero == k:
print 'this is k: {}'.format(k)
print v
return k

def print_return(func):
print func

x = find_location(my_dict)
print_return(x)

您必须向堆栈传递递归调用的结果:

if isinstance(v, dict):
return find_location(v)  # note the 'return'

如果没有return,该行只是一个调用函数但不返回结果(或结束周围函数(的语句。如果没有return语句,函数将隐式返回None

另一个答案是正确的,当函数递归时,您不会返回结果。

然而,有了这个添加,你的函数仍然不会返回你想要的答案,因为它永远不会超过循环的第一次迭代。如果第一个key != 'six',函数仍将返回None

def find_location(d):
for k, v in d.items():
if isinstance(v, dict):
key = find_location(v)
if (key == numero):
print(v)
return k
else:
return k

以上功能打印"hi"并返回"five">

最新更新