我有一个看似简单的递归函数,循环遍历字典字典.我想打印我的值v,因为我已经在做了,我想返回与此键关联的第一个键:值对.在这种情况下,代码输出v = 'hi'和None.我不确定为什么它一直没有返回.我将k变量设置为函数外部的空字符串.在这种情况下K应该是'six'.此外,我希望代码以某种方式返回,'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)
Run Code Online (Sandbox Code Playgroud)
您必须将递归调用的结果传递给堆栈:
if isinstance(v, dict):
return find_location(v) # note the 'return'
Run Code Online (Sandbox Code Playgroud)
如果没有return,则该行只是一个调用该函数但不返回其结果(或结束周围函数)的语句.如果没有return语句,函数会隐式返回None.