2020-02-03 17:25:54 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2020-09-17 12:09:59 +00:00
|
|
|
from benedict.core import clone
|
2020-02-03 17:25:54 +00:00
|
|
|
from benedict.utils import type_util
|
|
|
|
|
|
|
|
|
2020-02-05 09:30:19 +00:00
|
|
|
def _flatten_key(base_key, key, separator):
|
|
|
|
if base_key and separator:
|
|
|
|
return '{}{}{}'.format(base_key, separator, key)
|
|
|
|
return key
|
|
|
|
|
|
|
|
|
2020-02-03 17:25:54 +00:00
|
|
|
def flatten(d, separator='_', **kwargs):
|
2020-09-17 12:09:59 +00:00
|
|
|
new_dict = clone(d, empty=True)
|
2020-02-03 17:25:54 +00:00
|
|
|
keys = list(d.keys())
|
|
|
|
base_key = kwargs.pop('base_key', '')
|
|
|
|
for key in keys:
|
|
|
|
value = d.get(key, None)
|
2020-02-05 09:30:19 +00:00
|
|
|
new_key = _flatten_key(base_key, key, separator)
|
2020-02-03 17:25:54 +00:00
|
|
|
if type_util.is_dict(value):
|
|
|
|
new_value = flatten(value, separator=separator, base_key=new_key)
|
|
|
|
new_value.update(new_dict)
|
|
|
|
new_dict.update(new_value)
|
2020-02-05 09:30:19 +00:00
|
|
|
continue
|
|
|
|
new_dict[new_key] = value
|
2020-02-03 17:25:54 +00:00
|
|
|
return new_dict
|