Skip to content

Instantly share code, notes, and snippets.

@plammens
Created December 18, 2020 18:12
Show Gist options
  • Save plammens/79f865135ae901d1932862d750919353 to your computer and use it in GitHub Desktop.
Save plammens/79f865135ae901d1932862d750919353 to your computer and use it in GitHub Desktop.
Utility to flatten a dictionary with string values
from typing import Any, Dict, Union
NestedStringDict = Dict[str, Union[Any, "NestedStringDict"]]
def flatten_dict(nested: NestedStringDict, /, *, sep: str = "_") -> Dict[str, Any]:
"""
Flatten a nested dictionary with string keys.
The dictionary keys are strings and the values are either an arbitrary object or
another dictionary of this kind. The flattened dictionary's keys consist of the
concatenation of the path of keys (from nested dictionary to nested dictionary)
that reaches the value.
:param nested: Dictionary to flatten.
:param sep: Separator to use when concatenating nested keys.
:return: A flattened copy of ``d``.
Example:
>>> d = {"foo": 42, "bar": {"spam": 12, "eggs": 3}}
>>> flatten_dict(d)
{'foo': 42, 'bar_spam': 12, 'bar_eggs': 3}
>>> flatten_dict(d, sep=".")
{'foo': 42, 'bar.spam': 12, 'bar.eggs': 3}
"""
def iter_flat_pairs(d, prefix=""):
for key, value in d.items():
if isinstance(value, dict):
yield from iter_flat_pairs(value, prefix=key + sep)
else:
yield prefix + key, value
return dict(iter_flat_pairs(nested))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment