SHARE
TWEET

Untitled

a guest Jun 26th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import itertools
  2.  
  3.  
  4. def dict_product(d, repeat=1):
  5.     """Given a dictionary `d`, return a generator over every
  6.     combination of its values. This is very convenient for sweeping
  7.     over various values for the same key with multiple keys. The
  8.     values of `d` must all be lists or tuples (or other iterable)."""
  9.     # Set up items as (([k0, k0, ...], [v0-0, v0-1, ...]),
  10.     # ([k1, k1, ...], [v1-0, v1-1, ...]), (...), ...) pairs
  11.     all_items = (zip([k] * len(v), v) for k, v in d.items())
  12.     # Produce all combinations of hparams and map to dictionaries
  13.     return map(dict, itertools.product(*all_items, repeat=repeat))
  14.  
  15. # EXAMPLE
  16. # =======
  17. # Instead of writing this:
  18. for a in [1, 2, 3]:
  19.     for b in ['spec_a', 'spec_b']:
  20.         for c in [int, float]:
  21.             pass  # whatever
  22. # We can write this:
  23. abc = dict_product(dict(
  24.     a=[1, 2, 3],
  25.     b=['spec_a', 'spec_b'],
  26.     c=[int, float],
  27. ))
  28. # ...and do what we want here.
  29.  
  30. # The contents of abc (expanded) are:
  31. # [{'a': 1, 'b': 'spec_a', 'c': <class 'int'>},
  32. #  {'a': 1, 'b': 'spec_a', 'c': <class 'float'>},
  33. #  {'a': 1, 'b': 'spec_b', 'c': <class 'int'>},
  34. #  {'a': 1, 'b': 'spec_b', 'c': <class 'float'>},
  35. #  {'a': 2, 'b': 'spec_a', 'c': <class 'int'>},
  36. #  {'a': 2, 'b': 'spec_a', 'c': <class 'float'>},
  37. #  {'a': 2, 'b': 'spec_b', 'c': <class 'int'>},
  38. #  {'a': 2, 'b': 'spec_b', 'c': <class 'float'>},
  39. #  {'a': 3, 'b': 'spec_a', 'c': <class 'int'>},
  40. #  {'a': 3, 'b': 'spec_a', 'c': <class 'float'>},
  41. #  {'a': 3, 'b': 'spec_b', 'c': <class 'int'>},
  42. #  {'a': 3, 'b': 'spec_b', 'c': <class 'float'>}]
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top