0

given the following dictionary - which is dynamically so there could be any level of deepness (nested structure):

data = {
    "level": {
        "system": {
            "text": "A Lorem ipsum colour."
        },
        "board": {
            "core": {
                "text": "Another one."
            }
        }
    },
    "peer": {
        "core": {
            "text": "B Lorem ipsum colour."
        },
        "main": {
            "text": "C Lorem ipsum colour."
        }
    }
}

The goal is to extract the text elements orderd (from top to bottom), the result should be something like:

result = "A Lorem ipsum colour. Another one. B Lorem ipsum colour. C Lorem ipsum colour.

I think I've to use some type of recursion but I can't get it. What I get so far - and what is not working - is the following:

for k, v in data.items():
    if isinstance(v, dict):
        # i think i have to continue here on a deeper recursion level
    else:
        return v["text"]

Best regards

Sven
  • 141
  • 5
  • Does this answer your question? [Find all occurrences of a key in nested dictionaries and lists](https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-dictionaries-and-lists) – sahasrara62 Apr 10 '22 at 13:33
  • `return ' '.join(map(myfunc, v.values()))` is the recursion you want — but your base case isn’t quite right, since if `v` isn’t a dict then you can’t get its `text`. – Samwise Apr 10 '22 at 13:34

2 Answers2

2
def dict_value(val: dict):
    for key, item in val.items():
        if type(item) == dict:
            dict_value(item)
        else:
            print(item)


dict_value(data)
Ze'ev Ben-Tsvi
  • 1,174
  • 1
  • 3
  • 7
  • This works for the sample data given. However, it only works in this case because the 'text' keys are at the lowest level in the structure. If there were any other keys in the dictionary whose values were not dictionaries, it would print those as well. It also does not give the specified output. However, it is the accepted answer – DarkKnight Apr 10 '22 at 14:21
1

In order to get the result as stated in the original question:

data = {
    "level": {
        "system": {
            "text": "A Lorem ipsum colour."
        },
        "board": {
            "core": {
                "text": "Another one."
            }
        }
    },
    "peer": {
        "core": {
            "text": "B Lorem ipsum colour."
        },
        "main": {
            "text": "C Lorem ipsum colour."
        }
    }
}

def get_text(d, lst):
    for k, v in d.items():
        if isinstance(v, dict):
            get_text(v, lst)
        elif k == 'text':
            lst.append(v)
    return lst


print(' '.join(get_text(data, [])))

Output:

A Lorem ipsum colour. Another one. B Lorem ipsum colour. C Lorem ipsum colour.
DarkKnight
  • 19,739
  • 3
  • 6
  • 22