Skip to content

Instantly share code, notes, and snippets.

@0xnurl
Last active January 11, 2023 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xnurl/c3fcbc7a3b2900291c433ee60823c3fd to your computer and use it in GitHub Desktop.
Save 0xnurl/c3fcbc7a3b2900291c433ee60823c3fd to your computer and use it in GitHub Desktop.
Configuration dictionary grid search iterator with support for nested dictionaries
def iterate_grid_combinations(
grid: dict[str : Union[Iterable[Any], dict]]
) -> Iterator[dict[str, Any]]:
# language=rst
"""
:param grid: A dictionary specifying arguments and their values to iterate over in a grid-search way. Values can be nested dictionaries of same structure.
:return: A (lazy) generator iterating over all value combinations, including nested dicts.
Example:
``grid = {"name": ("John", "Mary"), "age": (10,20,30,40), "dogs": {"name": ("Rex", "Bobby"), "age": (3,4,5)}}``
```iterate_grid_combinations(grid)`` yields:
- ``{"name": "John", "age": 10, "dogs": {"name": "Rex", "age": 3}}``
- ``{"name": "John", "age": 11, "dogs": {"name": "Rex", "age": 3}}``
- ``...```
- ``{"name": "Mary", "age": 40, "dogs": {"name": "Bobby", "age": 5}}``
"""
nested_dicts_expanded = {
key: iterate_grid_combinations(val) if type(val) == dict else val
for key, val in grid.items()
}
arg_names = list(nested_dicts_expanded.keys())
arg_products = itertools.product(*nested_dicts_expanded.values())
for arg_product in arg_products:
yield {arg: val for arg, val in zip(arg_names, arg_product)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment