mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-07-24 01:44:31 +02:00
sqlite_utils.utils.flatten() function, closes #500
This commit is contained in:
parent
d792dad1cf
commit
34e75ed0dd
5 changed files with 40 additions and 23 deletions
|
|
@ -513,3 +513,21 @@ def hash_record(record: Dict, keys: Optional[Iterable[str]] = None):
|
|||
"utf8"
|
||||
)
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def _flatten(d):
|
||||
for key, value in d.items():
|
||||
if isinstance(value, dict):
|
||||
for key2, value2 in _flatten(value):
|
||||
yield key + "_" + key2, value2
|
||||
else:
|
||||
yield key, value
|
||||
|
||||
|
||||
def flatten(row: dict) -> dict:
|
||||
"""
|
||||
Turn a nested dict e.g. ``{"a": {"b": 1}}`` into a flat dict: ``{"a_b": 1}``
|
||||
|
||||
:param row: A Python dictionary, optionally with nested dictionaries
|
||||
"""
|
||||
return dict(_flatten(row))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue