Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools
- def dict_product(d, repeat=1):
- """Given a dictionary `d`, return a generator over every
- combination of its values. This is very convenient for sweeping
- over various values for the same key with multiple keys. The
- values of `d` must all be lists or tuples (or other iterable)."""
- # Set up items as (([k0, k0, ...], [v0-0, v0-1, ...]),
- # ([k1, k1, ...], [v1-0, v1-1, ...]), (...), ...) pairs
- all_items = (zip([k] * len(v), v) for k, v in d.items())
- # Produce all combinations of hparams and map to dictionaries
- return map(dict, itertools.product(*all_items, repeat=repeat))
- # EXAMPLE
- # =======
- # Instead of writing this:
- for a in [1, 2, 3]:
- for b in ['spec_a', 'spec_b']:
- for c in [int, float]:
- pass # whatever
- # We can write this:
- abc = dict_product(dict(
- a=[1, 2, 3],
- b=['spec_a', 'spec_b'],
- c=[int, float],
- ))
- # ...and do what we want here.
- # The contents of abc (expanded) are:
- # [{'a': 1, 'b': 'spec_a', 'c': <class 'int'>},
- # {'a': 1, 'b': 'spec_a', 'c': <class 'float'>},
- # {'a': 1, 'b': 'spec_b', 'c': <class 'int'>},
- # {'a': 1, 'b': 'spec_b', 'c': <class 'float'>},
- # {'a': 2, 'b': 'spec_a', 'c': <class 'int'>},
- # {'a': 2, 'b': 'spec_a', 'c': <class 'float'>},
- # {'a': 2, 'b': 'spec_b', 'c': <class 'int'>},
- # {'a': 2, 'b': 'spec_b', 'c': <class 'float'>},
- # {'a': 3, 'b': 'spec_a', 'c': <class 'int'>},
- # {'a': 3, 'b': 'spec_a', 'c': <class 'float'>},
- # {'a': 3, 'b': 'spec_b', 'c': <class 'int'>},
- # {'a': 3, 'b': 'spec_b', 'c': <class 'float'>}]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement