Last active
March 8, 2019 18:35
-
-
Save mark-mishyn/64cbdb820d4fa66d61d5c59b2abc09ee to your computer and use it in GitHub Desktop.
Convert dict to flat dict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
def flatten(d: dict, parent_key='', sep='__', flat_lists=False) -> dict: | |
""" | |
>>> flatten({'name': 'Ivan', 'mother': {'name': 'Alisha'}}) | |
{'name': 'Ivan', 'mother__name': 'Alisha'} | |
>>> flatten({'name': 'Ivan', 'brothers': [{'name': 'Jack'}]}, flat_lists=True) | |
{'name': 'Ivan', 'brothers_0__name': 'Jack'} | |
>>> flatten({'name': 'Ivan', 'brothers': ['Jack', 'Harry']}, flat_lists=True) | |
{'name': 'Ivan', 'brothers_0': 'Jack', 'brothers_1': 'Harry'} | |
>>> flatten({'name': 'Ivan', 'brothers': ['Jack', 'Harry']}, flat_lists=False) | |
{'name': 'Ivan', 'brothers': ['Jack', 'Harry']} | |
""" | |
if not isinstance(d, dict): | |
if flat_lists: | |
return {parent_key: d} | |
return d | |
res = {} | |
for k, v in d.items(): | |
new_key = parent_key + sep + k if parent_key else k | |
if isinstance(v, collections.MutableMapping): | |
res.update(flatten(v, new_key)) | |
elif isinstance(v, list): | |
if flat_lists: | |
for i, obj in enumerate(v): | |
res.update( | |
flatten(obj, '{}_{}'.format(new_key, i), sep=sep, flat_lists=flat_lists)) | |
else: | |
res[new_key] = [flatten(obj) for obj in v] | |
else: | |
res[new_key] = v | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment