I have a dictionary of lists, like {'a': [1, 2, 3], 'b': [5, 6, 7, 8]}
. There may by more than two key/value pairs in the actual data. I want to display an exhaustive list of dictionaries, one per line, where each dictionary has the same keys, and each value is an element chosen from the corresponding original list.
So for this input, the result would look like
{'a': 1, 'b': 5}
{'a': 1, 'b': 6}
...
{'a': 3, 'b': 8}
with a total of 3 * 4 = 12 lines of output.
I can do this for hard-coded key names:
for a, b in itertools.product(*p.itervalues()):
print({'a':a, 'b':b})
However, for the real data, I don't necessarily know the key names in advance, and there may be an unknown number of key-value pairs.
How can I fix the code so that it produces the desired dicts from the itertools.product
, regardless of the keys?
Instead of unpacking the product
results into separate variables, just zip
them with the original keys:
from itertools import product
for i in product(*p.values()):
print(dict(zip(p, i)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With