Python create combination of all dictionaries based on lists of values

Viewed 47

I would like to create dictionaries from a certain number of variable ranges as shown below.

I do have a really basic working solution but I was wondering if there was some more succinct way of expressing the same idea (I sense it could be solved with itertools maybe?)

a = [1, 2, 3]
b = ["me", "you", "her"]
c = range(1, 5)
d = ["mon", "tues", "wed"]

dic = {"a": None, "b": None, "c": None, "d": None}

for i in a:
    dic["a"] = i
    for j in b:
        dic["b"] = j
        for k in c:
            dic["c"] = k
            for l in d:
                dic["d"] = l
                print(dic)

Thanks

1 Answers

Take the cartesian product:

import itertools

a = [1, 2, 3]
b = ["me", "you", "her"]
c = range(1, 5)
d = ["mon", "tues", "wed"]

names = ["a", "b", "c", "d"]
vals = [a, b, c, d]

for comb in itertools.product(*vals):
    dic = dict(zip(names, comb))
    print(dic)

This uses zip to get an iterator of tuples where the first element is the name and the second element is the value, then uses the dict constructor to make a dictionary from an iterator of key/value pairs.

Related