All combinations of dictionary values

suggest change
options = {
	x: [a, b],
	y: [10, 20, 30]
}

Given a dictionary such as the one shown above, where there is a list representing a set of values to explore for the corresponding key. Suppose you want to explore "x"="a" with "y"=10, then "x"="a" with"y"=10, and so on until you have explored all possible combinations.

You can create a list that returns all such combinations of values using the following code.

import itertools

options = {
	x: [a, b],
	y: [10, 20, 30]
}

keys = options.keys()
values = (options[key] for key in keys)
combinations = [dict(zip(keys, combination)) for combination in itertools.product(*values)]
print combinations

This gives us the following list stored in the variable combinations:

[{'x': 'a', 'y': 10},
 {'x': 'b', 'y': 10},
 {'x': 'a', 'y': 20},
 {'x': 'b', 'y': 20},
 {'x': 'a', 'y': 30},
 {'x': 'b', 'y': 30}]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Dictionary:
* All combinations of dictionary values

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
26 Dictionary
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve