Home > Software engineering >  Python dict with lists as values, create list of dicts with all possible combinations of original ke
Python dict with lists as values, create list of dicts with all possible combinations of original ke

Time:07-27

I have a dict where all values are lists:

original_dict = {"key_00": [0, 1],
                    "key_01": [2, 3]
                    }

I want to get a list of dicts, where to each key is associated one of the original corresponding values, forming all the possible combinations...in other words, like this:

[
{"key_00": 0, "key_01": 2},
{"key_00": 0, "key_01": 3},
{"key_00": 1, "key_01": 2},
{"key_00": 1, "key_01": 3}
]

I tried using something like this:

res = []
for combs in product(*original_dict.values()):
    # zip used to perform cross keys combinations.
    res.append([{ele: cnt} for ele, cnt in zip(original_dict, combs)])

but this way I end up having

[{'key_00': 0}, {'key_01': 2}]
[{'key_00': 0}, {'key_01': 3}]
[{'key_00': 1}, {'key_01': 2}]
[{'key_00': 1}, {'key_01': 3}]    

CodePudding user response:

You can use list comprehesntion.

from itertools import product

original_dict = {"key_00": [0, 1],"key_01": [2, 3]}

res = [{ele: cnt for ele, cnt in zip(original_dict, combs)} 
       for combs in product(*original_dict.values())]

print(res)

Your code can fix like below:

res = []
for combs in product(*original_dict.values()):
    res.append({ele: cnt for ele, cnt in zip(original_dict, combs)})

[
    {'key_00': 0, 'key_01': 2}, 
    {'key_00': 0, 'key_01': 3}, 
    {'key_00': 1, 'key_01': 2}, 
    {'key_00': 1, 'key_01': 3}
]

CodePudding user response:

Try this

    res.append([{ele: cnt for ele, cnt in zip(original_dict, combs)}])

CodePudding user response:

You have to use itertools.product():

import itertools
original_dict = {"key_00": [0, 1],
                 "key_01": [2, 3]}

keys, values = zip(*original_dict.items())
aim = [dict(zip(keys, v)) for v in itertools.product(*values)]
print(aim)

>>> [{'key_00': 0, 'key_01': 2},
     {'key_00': 0, 'key_01': 3},
     {'key_00': 1, 'key_01': 2},
     {'key_00': 1, 'key_01': 3}]
  • Related