flatten the dictionary to a formatted string

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]}"

the result is then:

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top