Flatten and unflatten nested Python dictionaries using path notation. Zero dependencies.
python -m pip install -e .From source:
git clone https://github.com/nripankadas07/flatdict.git
cd flatdict
pip install -e .[dev]from flatdict import flatten, unflatten, get, set_
# Flatten nested → flat
flatten({"a": {"b": {"c": 1}}})
# -> {'a.b.c': 1}
# Unflatten flat → nested
unflatten({"a.b.c": 1, "a.b.d": 2})
# -> {'a': {'b': {'c': 1, 'd': 2}}}
# Custom separator
flatten({"a": {"b": 1}}, separator="/")
# -> {'a/b': 1}
# Expand lists into indexed paths
flatten({"users": [{"name": "ada"}, {"name": "lin"}]}, preserve_lists=False)
# -> {'users.0.name': 'ada', 'users.1.name': 'lin'}
# Get by path with default
data = {"a": {"b": {"c": 42}}}
get(data, "a.b.c") # 42
get(data, "a.x", default=None) # None
# Set by path, creating intermediate dicts
config: dict = {}
set_(config, "server.port", 8080)
set_(config, "server.host", "localhost")
# config -> {'server': {'port': 8080, 'host': 'localhost'}}Errors raise FlatDictError (a subclass of ValueError):
from flatdict import FlatDictError, unflatten
try:
unflatten({"a": 1, "a.b": 2})
except FlatDictError as exc:
print(f"conflict: {exc}")Walk a nested mapping and return a flat dict whose keys are joined paths.
data— aMappingto flatten.separator— string used to join path segments. Must be non-empty.preserve_lists— whenTrue(default), list/tuple values are kept as-is. WhenFalse, they are expanded using integer indices.
Raises FlatDictError if data is not a mapping, a key is not a string, or a key contains separator.
Reconstruct a nested dict from a flat path-keyed mapping.
data— a flat mapping whose keys are separator-joined paths.separator— path separator used indata.
Raises FlatDictError on empty keys, leading/trailing separators, duplicate leaves, or scalar/mapping conflicts.
Read a value from a nested mapping by path.
default— value to return if the path is missing. If omitted, aFlatDictErroris raised.
Write a value into a nested mapping by path, creating intermediate dicts as needed. Operates in place.
overwrite— whenFalse, raisesFlatDictErrorif the leaf already exists.
Raised on invalid input. Subclass of ValueError.
pip install -e .[dev]
pytestWith coverage:
pytest --cov=src/flatdict --cov-report=term-missingMIT — see LICENSE.