Home > Blockchain >  Product of Two Dict Values while retaining Dict Key
Product of Two Dict Values while retaining Dict Key

Time:09-13

I have a dictionary of an unknown amount of keys, and I'm trying to get the products of all the keys combined, while still retaining which list the items came from. For example

dicts = {
    "d1": ["d1_value", "d1_value2"],
    "d2": ["d2_value", "d2_value2"]
}

I am trying to get the product of the two lists, but their origin key retained.

result = [
    {
        "d1": "d1_value",
        "d2": "d2_value" 
    },
    {
        "d1": "d1_value",
        "d2": "d2_value2"
    },
    {
        "d1": "d1_value2",
        "d2": "d2_value"
    },
    {
        "d1": "d1_value2",
        "d2": "d2_value2"

    }
]

Anyone have any ideas?

CodePudding user response:

Looks like you can use itertools.product with a nested comprehension:

[{k: v for k, v in zip(dicts.keys(), p)} for p in product(*dicts.values())]

This works because the keys and values iterators of a dictionary are guaranteed to be in the same order, regardless of the ordering of the dictionary. That means that the elements of the tuple p will be in value order, which is the same order as the keys. The output will contain all of the outputs, but in python versions before 3.6, the output may be "shuffled", depending on the arbitrary ordering of the dictionary keys.

An alternative phrasing is

[dict(zip(dicts, p)) for p in product(*dicts.values())]
  • Related