Skip to content

Instantly share code, notes, and snippets.

@SimiCode
Created Sep 5, 2019
Embed
What would you like to do?
Flatten a nested dictionary in python
def flatten(nested, column_names):
all_dicts = []
final_result = {}
index = 0
def recurse(data):
for k, v in data.items():
final_result = {}
if isinstance(v, dict):
if any(isinstance(i,dict) for i in v.values()):
recurse(v)
else:
final_result.update(v)
all_dicts.append(final_result.copy())
else:
final_result[k]=v
all_dicts.append(final_result.copy())
recurse(nested)
return all_dicts
def flatten2(nested, column_names):
all_dicts = []
final_result = {}
index = 0
def recurse(data, existing = []):
for k, v in data.items():
final_result = {}
if isinstance(v, dict):
if any(isinstance(i,dict) for i in v.values()):
existing.append(k)
recurse(v, existing=existing)
else:
final_result.update(v)
final_result.update(zip(column_names[:len(existing)], existing))
all_dicts.append(final_result.copy())
else:
final_result[k]=v
final_result.update(zip(column_names[:len(existing)], existing))
all_dicts.append(final_result.copy())
recurse(nested)
return all_dicts
a = {
'foo': {
'cat': {'name': 'Hodor', 'age': 7},
'dog': {'name': 'Mordor', 'age': 5},
},
'bar': {
'rat': {'name': 'Izidor', 'age': 3},
'ratv': {'nameb': 'Izidor', 'age': 3},
},
'baz': 'woops',
}
print(flatten(a, ['foobar', 'animal']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment