Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.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 在dictrionaries中搜索字典中的值_Python_Dictionary_Search - Fatal编程技术网

Python 在dictrionaries中搜索字典中的值

Python 在dictrionaries中搜索字典中的值,python,dictionary,search,Python,Dictionary,Search,我对python非常陌生,不知道是否有一种简单的方法可以在字典中为字典的特定键找到值。我相信你可以写一个循环等等,但是想知道是否有更直接的方法,特别是如果有多个层,并且你不知道值在哪里 比方说,如果我想找到“母亲”的价值 a = {'family 1':{'Father':'Joe', 'Mother': 'Eva'}} 非常感谢 def recursive_lookup(d, key): if key in d: return d[key] for v in

我对python非常陌生,不知道是否有一种简单的方法可以在字典中为字典的特定键找到值。我相信你可以写一个循环等等,但是想知道是否有更直接的方法,特别是如果有多个层,并且你不知道值在哪里

比方说,如果我想找到“母亲”的价值

a = {'family 1':{'Father':'Joe', 'Mother': 'Eva'}}
非常感谢

def recursive_lookup(d, key):
    if key in d:
        return d[key]
    for v in d.values():
        if not isinstance(v, dict):
            continue
        x = recursive_lookup(v, key)
        if x is not None:
            return x
    return None
这可以按如下方式使用:

>>> d = {'family 1': {'Father': 'Joe', 'Mother': 'Eva'}}
>>> recursive_lookup(d, "Mother")
'Eva'
这可以按如下方式使用:

>>> d = {'family 1': {'Father': 'Joe', 'Mother': 'Eva'}}
>>> recursive_lookup(d, "Mother")
'Eva'

a[“family 1”][“Mother”]
您可以编写一个函数并将其命名为
recursive\u lookup
a[“family 1”][“Mother”]
您可以编写一个函数并将其命名为
recursive\u lookup
。谢谢-这很有意义。我更想知道的是,是否有内置的函数可以实现这一点,谢谢-有意义。我更想知道是否有内置函数可以实现这一点