Skip to content

Instantly share code, notes, and snippets.

@honno
Created April 9, 2023 22:16
Show Gist options
  • Save honno/6b82cb08a9d23ec458ab9f82ff9c396d to your computer and use it in GitHub Desktop.
Save honno/6b82cb08a9d23ec458ab9f82ff9c396d to your computer and use it in GitHub Desktop.
from typing import Dict, Iterator, Tuple, TypeVar, Union
K = TypeVar("K")
V = TypeVar("V")
NestedDict = Union[V, Dict[K, Union["NestededDict", V]]]
def flatten_nested(
nested: NestedDict, parent_keys: Tuple[K, ...] = ()
) -> Iterator[Tuple[Tuple[K, ...], V]]:
if isinstance(nested, dict):
for key, value in nested.items():
keys = parent_keys + (key,)
yield from flatten_nested(value, parent_keys=keys)
else:
yield parent_keys, nested
if __name__ == "__main__":
for nested, expected in [
("foo", [((), "foo")]),
({"a": "foo"}, [(("a",), "foo")]),
({"a": {"b": "foo"}}, [(("a", "b"), "foo")]),
]:
assert list(flatten_nested(nested)) == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment