flatten dictionary to formatted string

Viewed 63

I am stuck on this problem for a long time.

Let's say we have a python dictionary as follows:

d = {'TOP': [{'S': [{'NP-TMP': [{'NP': [{'DT': ['This']}, {'NN': ['time']}]},
                        {'ADVP': [{'RP': ['around']}]}]},
            {'NP-SBJ': [{'PRP': ['they']}]},
            {'VP': [{'VBP': ["'re"]},
                    {'VP': [{'VBG': ['moving']},
                            {'ADVP': [{'RB': ['even']},
                                      {'RBR': ['faster']}]}]}]}]}]}

I want to convert it into the following format:

(((((This)(time))((around)))((they))(('re)((moving)((even)(faster))))))

I tried the following code, but am not able to proceed further.

for tree in d.values():
    for i, j in tree[0].items():
        for n in j:
            for p in n.items():
                print(p)
1 Answers

a recursive generator would work (not very nice, though...)

def sub(dct):
    for lst in dct.values():
        for item in lst:
            if isinstance(item, str):
                yield f"{item}"
            elif isinstance(item, dict):
                yield "("
                yield from sub(item)
                yield ")"
            elif isinstance(item, list):
                assert len(item) == 1
                yield f"{item[0]}"
            else:
                pass

the result is then:

r = f"({''.join(sub(d))})"
print(r)
# (((((This)(time))((around)))((they))(('re)((moving)((even)(faster))))))
Related