How can I find the value of the key in a recursive dictionary?

I wrote a recursive function to find a value with data dict

and key

. But I think there should be a more readable version. Here's a block of code.

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")

      

Is there any one version of this or using yield (not sure about this)?

Edit : Based on recursive functions and add / extension lists and ideas from comments. I modified the function to find all matched values ​​using a given key

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]

      

+3


source to share


2 answers


Edit:

Recursively searching for (nested) dict (s) through list comprehension:

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

      

^ Returns (nested) lists of values ​​for each matching (nested) dict key.


A simplified version that prints, rather than returns, each match:

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])

      

^ Just displays the values ​​for each matching key as they occur.


Test using



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

      



<Hitp> def findvalue (dict, key, target): if dict [key] == target: return True return False

Check it:

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

      

Strike>

0


source


To find the value of the first key (found in Breadth First Search) of a python recursive dictionary.

You can do:

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))

      

Example:



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'))

      

Output:

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

      

+2


source







All Articles