-2

I wrote this python function:

d ={'key1':{'key2':{'key11':{'key12':'value13'}}},'key3':[{'key4':'value2', 'key5': 'value3'}]}
key_path = 'key1.key2.key11.key12'


def recursive_search(d, key_path):
    key_parts = key_path.split('.')
    if len(key_parts) == 1:
        return d.get(key_parts[0])
    elif isinstance(d.get(key_parts[0]), dict):
        recursive_search(d.get(key_parts[0]), '.'.join(key_parts[1:]))
    elif isinstance(d.get(key_parts[0]), list):
        for i in d.get(key_parts[0]):
            for key in i.keys():
                if key == key_parts[1]:
                    recursive_search(i, '.'.join(key_parts[1:]))

x = recursive_search(d, 'key3.key4')

I'm expecting to return 'value2' but nothing is returned. What am I doing wrong?

Blue Moon
  • 4,421
  • 20
  • 52
  • 91
  • `recursive_search(i, '.'.join(key_parts[1:]))` should be `return recursive_search(i, '.'.join(key_parts[1:]))` (similarly in both places) – Adrian W Jul 25 '20 at 13:37
  • The values returned by the inner calls to "recursive_search" aren't `return`ed by the outer calling function instance. – Michael Butscher Jul 25 '20 at 13:39
  • If you're going to use this function for production purposes I highly recommend this library instead of implementing this functionality from scratch. https://glom.readthedocs.io/en/latest/ – mehdy Jul 25 '20 at 13:39

1 Answers1

3

You are not returning anything when you invoke recursive_search recursively. Add return and it would work fine

d ={'key1':{'key2':{'key11':{'key12':'value13'}}},'key3':[{'key4':'value2', 'key5': 'value3'}]}
key_path = 'key1.key2.key11.key12'


def recursive_search(d, key_path):
    key_parts = key_path.split('.')
    if len(key_parts) == 1:
        return d.get(key_parts[0])
    elif isinstance(d.get(key_parts[0]), dict):
        return recursive_search(d.get(key_parts[0]), '.'.join(key_parts[1:]))
    elif isinstance(d.get(key_parts[0]), list):
        for i in d.get(key_parts[0]):
            for key in i.keys():
                if key == key_parts[1]:
                    return recursive_search(i, '.'.join(key_parts[1:]))

x = recursive_search(d, 'key3.key4')
print (x)

Output

value2
Prem Anand
  • 2,469
  • 16
  • 16