Skip to content

Instantly share code, notes, and snippets.

@phinate
Created December 12, 2025 13:08
Show Gist options
  • Select an option

  • Save phinate/05f0e254974b2ed9f47f51d686ba4285 to your computer and use it in GitHub Desktop.

Select an option

Save phinate/05f0e254974b2ed9f47f51d686ba4285 to your computer and use it in GitHub Desktop.
flatten dict keys into dot notation
def _flatten_dict(dct: dict[str, Any]) -> list[str]:
# for each key:
# - find values
# - if dict: recurse
# - elif list: recurse for each item
# - else: check if bool.
# - if bool and True, compose a string that you pass around
# to join the param names.
# This was coded for a specific use-case and YAML design; it should
# be fairly straightforward to adapt to produce just the keys.
def recur(entry, dot_str: str = "") -> list[str] | str | None:
if isinstance(entry, bool):
if entry:
return dot_str
return None
dot_strs: list[str] = []
if isinstance(entry, dict):
for key in entry:
passed_str = dot_str + f".{key}" if dot_str else key
res = recur(entry[key], passed_str)
if res is not None:
if isinstance(res, list):
dot_strs += res
else:
dot_strs.append(res)
return dot_strs
if isinstance(entry, list):
for i, e in enumerate(entry):
res = recur(e, dot_str + f".{i}")
if res is not None:
if isinstance(res, list):
dot_strs += res
else:
dot_strs.append(res)
return dot_strs
msg = "Ignore config should only have entries with `True` or `False` to ignore or not ignore validation."
raise ValueError(msg)
return recur(dct)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment