【问题标题】:Search for values in dictionaries within dictrionaries在字典中搜索字典中的值
【发布时间】:2020-07-13 04:45:06
【问题描述】:

我对 python 很陌生,想知道是否有一种简单的方法可以为字典中的字典的特定键找到值。我相信您可以编写一个循环等,但想知道是否有更直接的方法,特别是如果有多个层并且您不知道值的确切位置?

假设我想找到“母亲”的值

a = {'family 1':{'Father':'Joe', 'Mother': 'Eva'}}

非常感谢。

【问题讨论】:

  • a["family 1"]["Mother"]
  • 您可以编写一个函数并将其命名为recursive_lookup

标签: python dictionary search


【解决方案1】:
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'

【讨论】:

  • 谢谢 - 有道理。我更想知道是否有内置函数可以做到这一点
猜你喜欢
  • 2017-10-02
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多