Skip to content

Instantly share code, notes, and snippets.

@kasperfred kasperfred/merge_dicts.py
Last active Sep 23, 2017

Embed
What would you like to do?
def flatten(obj):
flat = []
if hasattr(obj, '__iter__'):
for i in obj:
flat.extend(flatten(i))
else:
flat.append(obj)
return flat
def merge_dicts(list_of_dicts, flat=True):
merge_dict = {}
for d in list_of_dicts:
for col in d:
try:
if flat:
merge_dict[col].extend(flatten(d[col]))
else:
merge_dict[col].append(d[col])
except KeyError:
if flat:
merge_dict[col] = flatten(d[col])
else:
merge_dict[col] = [d[col]]
return merge_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.