Created
April 9, 2023 22:16
-
-
Save honno/6b82cb08a9d23ec458ab9f82ff9c396d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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