6

I have a dictionary of lists:

In [72]: params
Out[72]: {'a': [1, 2, 3], 'b': [5, 6, 7, 8]}

I may have more than two key/value pairs. I want to create a list of dictionaries which gives me all the possible combinations of the the lists corresponding to a and b:

e.g.

[{'a':1, 'b'=5}, 
{'a':1, 'b'=6},
{'a':1, 'b'=7},
 ...
{'a':3, 'b'=8},]

I can do this by hard coding the keys:

for a,b in itertools.product(*p.itervalues()):
    print {'a':a, 'b':b}

But I don't want to hard code as

  1. I don't know how many key/value pairs there are and
  2. I don't necessarily know the names in advanced
mchangun
  • 9,104
  • 18
  • 68
  • 95

1 Answers1

12

You're close:

from itertools import product, izip

for i in product(*p.itervalues()):
    print dict(izip(p, i))

{'a': 1, 'b': 5}
{'a': 1, 'b': 6}
...
{'a': 3, 'b': 8}
Jayanth Koushik
  • 9,006
  • 1
  • 38
  • 49
  • I actually have a doubt about this. Is the 'order' going to be the same for both `p.values` and `p.keys`? – Jayanth Koushik Jun 11 '14 at 06:42
  • 1
    I was actually going to answer my own question with that solution but I was unsure on the order of p.keys. I somehow have the feeling that it's not reliable! – mchangun Jun 11 '14 at 06:44
  • Checkout `__iter__()` in ParameterGrid https://github.com/scikit-learn/scikit-learn/blob/0.14.X/sklearn/grid_search.py. Exactly what I want. – mchangun Jun 11 '14 at 06:46
  • 1
    You can zip `p` with `i` directly and save the time spent on repeatedly creating the list of keys. – user2357112 Jun 11 '14 at 07:00
  • Damn, the Python is just too powerful. I spent half an hour working out a recursive solution due to my lack of practice with the itertools. – timgeb Jun 11 '14 at 07:35