Created
March 20, 2023 13:51
-
-
Save shner-elmo/b2900b265df950d32f4ce6a5c8f6f2d6 to your computer and use it in GitHub Desktop.
Get the path of each key in a dictionary
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 __future__ import annotations | |
from typing import Iterator, TypeVar | |
T = TypeVar('T') | |
def get_dict_keys_path(dct: dict[T, ...], keys: list[T] | None = None) -> Iterator[T]: | |
if keys is None: | |
keys = [] | |
for k, v in dct.items(): | |
keys.append(k) | |
yield ''.join([f"['{x}']" for x in keys[:]]) | |
if isinstance(v, dict): | |
yield from get_dict_keys_path(dct=v, keys=keys) | |
keys.pop() | |
# example: | |
dct = { | |
'a': { | |
'b': { | |
'b1': {}, | |
'b2': {} | |
}, | |
'c': { | |
'c1': {} | |
} | |
} | |
} | |
for x in get_dict_keys_path(dct): | |
print(x) | |
['a'] | |
['a']['b'] | |
['a']['b']['b1'] | |
['a']['b']['b2'] | |
['a']['c'] | |
['a']['c']['c1'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment