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-09-17 17:01:57 +00:00
|
|
|
def _flatten_item(d, base_dict, base_key, separator):
|
|
|
|
new_dict = base_dict
|
2020-02-03 17:25:54 +00:00
|
|
|
keys = list(d.keys())
|
|
|
|
for key in keys:
|
2020-02-05 09:30:19 +00:00
|
|
|
new_key = _flatten_key(base_key, key, separator)
|
2020-09-17 17:01:57 +00:00
|
|
|
value = d.get(key, None)
|
2020-02-03 17:25:54 +00:00
|
|
|
if type_util.is_dict(value):
|
2021-10-12 12:27:35 +00:00
|
|
|
new_value = _flatten_item(
|
|
|
|
value, base_dict=new_dict, base_key=new_key, separator=separator
|
|
|
|
)
|
2020-02-03 17:25:54 +00:00
|
|
|
new_dict.update(new_value)
|
2020-02-05 09:30:19 +00:00
|
|
|
continue
|
2020-09-17 17:01:57 +00:00
|
|
|
if new_key in new_dict:
|
|
|
|
raise KeyError(
|
2021-10-12 12:27:35 +00:00
|
|
|
'Invalid key: "{}", key already in flatten dict.'.format(new_key)
|
|
|
|
)
|
2020-02-05 09:30:19 +00:00
|
|
|
new_dict[new_key] = value
|
2020-02-03 17:25:54 +00:00
|
|
|
return new_dict
|
2020-09-17 17:01:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
def flatten(d, separator='_'):
|
|
|
|
new_dict = clone(d, empty=True)
|
2021-10-12 12:27:35 +00:00
|
|
|
return _flatten_item(d, base_dict=new_dict, base_key='', separator=separator)
|