python-benedict/benedict/core/flatten.py

32 lines
978 B
Python
Raw Normal View History

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 f"{base_key}{separator}{key}"
2020-02-05 09:30:19 +00:00
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:
2023-03-01 16:37:50 +00:00
raise KeyError(f"Invalid key: {new_key!r}, key already in flatten dict.")
2020-02-05 09:30:19 +00:00
new_dict[new_key] = value
return new_dict
2022-02-13 10:35:43 +00:00
def flatten(d, separator="_"):
new_dict = clone(d, empty=True)
2022-02-13 10:35:43 +00:00
return _flatten_item(d, base_dict=new_dict, base_key="", separator=separator)