Flattening a nested dictionary in Python
June 1, 2021•78 words
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)