Skip to content Skip to sidebar Skip to footer

How Do You Turn A Dict Of Lists Into A List Of Dicts With All Combinations?

Basically what I am looking for is the equivalent of itertools.product but for dicts. For example, say I want to test a function for all combinations of its keyword arguments, I wo

Solution 1:

This is what I have come up with:

from itertools import product

def dictproduct(dct):
    for t in product(*dct.itervalues()):
        yield dict(zip(dct.iterkeys(), t))

which gives us

>>> list(dictproduct({"debug":["on", "off"], "locale":["de_DE", "en_US", "fr_FR"]}))
[{'debug': 'on', 'locale': 'de_DE'},
 {'debug': 'on', 'locale': 'en_US'},
 {'debug': 'on', 'locale': 'fr_FR'},
 {'debug': 'off', 'locale': 'de_DE'},
 {'debug': 'off', 'locale': 'en_US'},
 {'debug': 'off', 'locale': 'fr_FR'}]

This can also be used to efficiently call a function with all combinations of keyword arguments:

def kwproduct(**kwargs):
    return dictproduct(kwargs)

def f(x, y):
    return 10*x + y

for kwargs in kwproduct(x=[1,2], y=[3,4,5]):
    print "f({x},{y})={z}".format(z=f(**kwargs), **kwargs)

output:

f(1,3)=13
f(2,3)=23
f(1,4)=14
f(2,4)=24
f(1,5)=15
f(2,5)=25

The benefit of kwproduct over dictproduct is that you don't need to create a dict but it obviously limits you to use valid argument names as keys.


Post a Comment for "How Do You Turn A Dict Of Lists Into A List Of Dicts With All Combinations?"