Skip to content

Commit

Permalink
refactor(framework:skip) Add function to unflatten dicts (#3974)
Browse files Browse the repository at this point in the history
  • Loading branch information
charlesbvll authored Aug 9, 2024
1 parent afa06cf commit 26ba030
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/py/flwr/common/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,23 @@ def flatten_dict(
return dict(items)


def unflatten_dict(flat_dict: Dict[str, Any]) -> Dict[str, Any]:
"""Unflatten a dict with keys containing separators into a nested dict."""
unflattened_dict: Dict[str, Any] = {}
separator: str = "."

for key, value in flat_dict.items():
parts = key.split(separator)
d = unflattened_dict
for part in parts[:-1]:
if part not in d:
d[part] = {}
d = d[part]
d[parts[-1]] = value

return unflattened_dict


def parse_config_args(
config: Optional[List[str]],
separator: str = ",",
Expand Down
8 changes: 8 additions & 0 deletions src/py/flwr/common/config_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
get_project_config,
get_project_dir,
parse_config_args,
unflatten_dict,
)

# Mock constants
Expand Down Expand Up @@ -229,6 +230,13 @@ def test_flatten_dict() -> None:
assert flatten_dict(raw_dict) == expected


def test_unflatten_dict() -> None:
"""Test unflatten_dict with a flat dictionary."""
raw_dict = {"a.b.c": "d", "e": "f"}
expected = {"a": {"b": {"c": "d"}}, "e": "f"}
assert unflatten_dict(raw_dict) == expected


def test_parse_config_args_none() -> None:
"""Test parse_config_args with None as input."""
assert not parse_config_args(None)
Expand Down

0 comments on commit 26ba030

Please sign in to comment.