python-benedict/benedict/core/flatten.py

36 lines
1.0 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
from benedict.core import clone
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
def _flatten_item(d, base_dict, base_key, separator):
new_dict = base_dict
keys = list(d.keys())
for key in keys:
2020-02-05 09:30:19 +00:00
new_key = _flatten_key(base_key, key, separator)
value = d.get(key, None)
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
)
new_dict.update(new_value)
2020-02-05 09:30:19 +00:00
continue
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
return new_dict
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)