Flattening a nested dictionary in Python

I've always hated recursive logic because it makes my brain hurt.

This is relatively straightforward approach to flattening a nested dictionary by recursively passing the value of a dictionary back to itself if it is itself a dictionary.

d = {

def flatten(d, parent_key=''):
    output = []
    for k,v in d.items():
        new_key = k + parent_key
        if isinstance(v, dict):
            output.extend(flatten(v, new_key).items())
            output.append((new_key, v))
    return dict(output)

test = flatten(d)

You'll only receive email when they publish something new.

More from data // software // tech