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 = {
    'a':1,
    'b':2,
    'c':{
        'a':1
    }
}


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())
        else:
            output.append((new_key, v))
    return dict(output)


test = flatten(d)
print(test)

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

More from data // software // tech
All posts