Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary of lists to Dictionary

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?

like image 412
mchangun Avatar asked Jun 11 '14 06:06

mchangun


1 Answers

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)))
like image 56
Jayanth Koushik Avatar answered Sep 25 '22 14:09

Jayanth Koushik