Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(framework:skip) Add function to unflatten dicts #3974

Merged
merged 3 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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