【问题标题】:How can I search the value of a key on a recursive dictionary?如何在递归字典中搜索键的值?
【发布时间】:2017-12-02 13:12:42
【问题描述】:

我编写了一个递归函数来查找给定dictkey 的值。 但我认为应该有一个更具可读性的版本。这是代码块。

def findvalue(_dict, target):
    for key, values in _dict.items():
        if 'dict' in str(type(values)):
            return findvalue(values, target)
        elif key == target:
            return values
        else:
            print("no such key")

是否有任何单行版本或使用产量(不确定)?

编辑:基于 Recursive functions and lists appending/extending 和 cmets 的想法,我修改了函数以通过给定键查找所有匹配值

def find_all_value(_dict, target, values=None):
    for key, values in _dict.items():
        #case 1: it is a dictionary but not match the key
        if isinstance(values, dict) and key!=target:
            return find_all_value(values, target)
        #case 2: it is a dictionary but match the key -> put it in result
        elif isinstance(values, dict) and key==target:
            return [values] + find_all_value(values, target)
        #case 3: it is not dictionary and match the key -> put it in result
        elif key==target:
            return [values]

【问题讨论】:

  • 我认为您的代码不起作用。您正在valuesstr(type()) 中搜索文字字符串值'dict'。所以您基本上是在做if 'dict' in '<class 'list'>',我敢肯定这不是您想要的。
  • 第一个“if”用于检查它是否是字典类型。如果不是字典,则检查key==target,如果为true,则返回值(可以是dict以外的任何类型)

标签: python dictionary recursion


【解决方案1】:

编辑:

通过列表理解递归搜索(嵌套)dict:

def findvalue(d, key):

    l = [e for e in [findvalue(e, key) for e in [d[k] for k in d.keys() if type(d[k])==dict]] if e]
    l.append(d[key]) if key in d else l
    return l

^ 返回(嵌套)每个匹配(嵌套)dict 键的值列表。


打印而不是返回每个匹配项的简化版本:

def findvalue(d, key):

    [findvalue(e, key) for e in [d[k] for k in d.keys() if type(d[k])==dict]]
    if key in d: print(d[key])

^ 只显示每个匹配键的值,因为它们 遇到了。


测试:

d = {1:2, 3:4, 5:{6:7,8:9, 99:{100:101}}, 10:11}



def findvalue(字典,键,目标): 如果 dict[key] == 目标:返回 True 返回错误

测试一下:

dict = {1:2,3:4}
findvalue(dict,3,4)

【讨论】:

  • 这个看起来不错但是只能处理1个深度的情况。如果它可以检查嵌套字典那就更好了
  • @PoonKingSing 更新:抱歉回复延迟。
【解决方案2】:

找到递归python字典的第一个键(在广度优先搜索中找到)的值。

你可以这样做:

def find_value(_dict, key):
    stack = [(None, _dict)]
    while len(stack) != 0:
        _key, val = stack.pop(0)
        if val is not _dict and _key == key:
            return val
        if isinstance(val, dict):
            for k, v in val.items():
                stack.append((k, v))

例子:

d = {'c': {'d': 3, 'e': 4}, None: 0, 'b': 2, 'a': 1}

print('None:', find_value(d, None))
print('c:', find_value(d, 'c'))
print('e:', find_value(d, 'e'))
print('a:', find_value(d, 'a'))

输出:

None: 0
c: {'e': 4, 'd': 3}
e: 4
a: 1

【讨论】:

  • 这是一个更完整的版本,如果键是字典,它也可以处理返回值。
猜你喜欢
  • 1970-01-01
  • 2016-08-16
  • 2018-09-28
  • 2016-11-22
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2020-12-17
相关资源
最近更新 更多