Skip to content

Instantly share code, notes, and snippets.

@edison12a
Created September 5, 2019 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edison12a/c2b7949004d8082fb5695271ab9998c5 to your computer and use it in GitHub Desktop.
Save edison12a/c2b7949004d8082fb5695271ab9998c5 to your computer and use it in GitHub Desktop.
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