Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 值从函数返回为无_Python_Python 3.x - Fatal编程技术网

Python 值从函数返回为无

Python 值从函数返回为无,python,python-3.x,Python,Python 3.x,我试图从嵌套字典中获取用户输入定义键的值。 而我能够从函数本身打印出值。Return语句将值发送为None people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}, 3: 'James', 4: 'lance', 'change1': {5: 'place

我试图从嵌套字典中获取用户输入定义键的值。 而我能够从函数本身打印出值。Return语句将值发送为None

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
          3: 'James',
          4: 'lance',
          'change1': {5: 'place'},
          'country': {'Waterloo': 'Waterloo', 'Australia': 'Australia'},
          6: {'Position': 'GM'}
          }

def getfromdict(mydict, mykey):
    for i in mydict.keys():

        if type(mydict[i])==dict:
            newdict = mydict[i]
            getfromdict(newdict, mykey)

        elif i == mykey:
            print(mydict[i])
            valuefound = mydict[i]
            return valuefound

        else:
            continue

result = getfromdict(people,5)
print(result)

代码段的第三行应该是

           return getfromdict(newdict, mykey)
在树上找到一片叶子,你可以

def leaf(tree, key):
    if key in tree: return tree[key]
    for subtree in filter(lambda s: isinstance(s, dict), tree.values()):
        ret_val = leaf(subtree, key)
        if ret_val is not None: return ret_val

这个实现的特性是,如果在某个级别找到一个键,无论它指向什么,都会返回一个叶或子树(在不需要的情况下,修复非常简单)。

您可以尝试在嵌套的JSON中搜索键

 def getfromdict(mydict, mykey):
    if type(mydict) == type({}):
        for k1 in mydict:
            if k1 == mykey:
                return mydict[k1]
            fromdict = getfromdict(mydict[k1], mykey)
            if fromdict is not None:
                return fromdict

如果您尝试运行代码,它将无法工作,因为它会在第一个嵌套循环中兴奋起来。这是代码执行的输出:-->place None Process finished with exit code 0是否尝试了我的回答您是否可以将此解决方案标记为已回答,因为另一个解决方案具有误导性或误导性