Created
June 4, 2020 05:29
-
-
Save answerquest/fbbc2fea4ea6595de4f1ce767b50566b to your computer and use it in GitHub Desktop.
flatten_hierarchical_dict.py : convert any nested json with arrays / empty elements also into flat json (brought into python so dicts)
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
| # see https://stackoverflow.com/a/62186294/4355695 for full explanation | |
| # adapted from https://github.com/ScriptSmith/socialreaper/blob/master/socialreaper/tools.py#L8 | |
| import collections | |
| crumbs = True | |
| def flatten(dictionary, parent_key=False, separator='.'): | |
| """ | |
| Turn a nested dictionary into a flattened dictionary | |
| :param dictionary: The dictionary to flatten | |
| :param parent_key: The string to prepend to dictionary's keys | |
| :param separator: The string used to separate flattened keys | |
| :return: A flattened dictionary | |
| """ | |
| items = [] | |
| for key, value in dictionary.items(): | |
| if crumbs: print('checking:',key) | |
| new_key = str(parent_key) + separator + key if parent_key else key | |
| if isinstance(value, collections.MutableMapping): | |
| if crumbs: print(new_key,': dict found') | |
| if not value.items(): | |
| if crumbs: print('Adding key-value pair:',new_key,None) | |
| items.append((new_key,None)) | |
| else: | |
| items.extend(flatten(value, new_key, separator).items()) | |
| elif isinstance(value, list): | |
| if crumbs: print(new_key,': list found') | |
| if len(value): | |
| for k, v in enumerate(value): | |
| items.extend(flatten({str(k): v}, new_key).items()) | |
| else: | |
| if crumbs: print('Adding key-value pair:',new_key,None) | |
| items.append((new_key,None)) | |
| else: | |
| if crumbs: print('Adding key-value pair:',new_key,value) | |
| items.append((new_key, value)) | |
| return dict(items) | |
| # test it | |
| ans = flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3], 'e':{'f':[], 'g':{}} }) | |
| print('\nflattened:',ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment