| Total Complexity | 6 |
| Total Lines | 27 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | # -*- coding: utf-8 -*- |
||
| 2 | |||
| 3 | from benedict.utils import type_util |
||
| 4 | |||
| 5 | |||
| 6 | def _flatten_key(base_key, key, separator): |
||
| 7 | if base_key and separator: |
||
| 8 | return '{}{}{}'.format(base_key, separator, key) |
||
| 9 | return key |
||
| 10 | |||
| 11 | |||
| 12 | def flatten(d, separator='_', **kwargs): |
||
| 13 | new_dict = d.copy() |
||
| 14 | new_dict.clear() |
||
| 15 | keys = list(d.keys()) |
||
| 16 | base_key = kwargs.pop('base_key', '') |
||
| 17 | for key in keys: |
||
| 18 | value = d.get(key, None) |
||
| 19 | new_key = _flatten_key(base_key, key, separator) |
||
| 20 | if type_util.is_dict(value): |
||
| 21 | new_value = flatten(value, separator=separator, base_key=new_key) |
||
| 22 | new_value.update(new_dict) |
||
| 23 | new_dict.update(new_value) |
||
| 24 | continue |
||
| 25 | new_dict[new_key] = value |
||
| 26 | return new_dict |
||
| 27 |