Combine renaming a Python dictionary into a list of dictionaries

Given a dictionary that looks like this:

{ 'Color': ['Red', 'Yellow'], 'Size': ['Small', 'Medium', 'Large'] } 

How to create a list of dictionaries that combines the different values โ€‹โ€‹of the first keys of a dictionary? I want:

 [ {'Color': 'Red', 'Size': 'Small'}, {'Color': 'Red', 'Size': 'Medium'}, {'Color': 'Red', 'Size': 'Large'}, {'Color': 'Yellow', 'Size': 'Small'}, {'Color': 'Yellow', 'Size': 'Medium'}, {'Color': 'Yellow', 'Size': 'Large'} ] 
+7
source share
2 answers

I think you want a Cartesian product, not a permutation, in which case itertools.product can help:

 >>> from itertools import product >>> d = {'Color': ['Red', 'Yellow'], 'Size': ['Small', 'Medium', 'Large']} >>> [dict(zip(d, v)) for v in product(*d.values())] [{'Color': 'Red', 'Size': 'Small'}, {'Color': 'Red', 'Size': 'Medium'}, {'Color': 'Red', 'Size': 'Large'}, {'Color': 'Yellow', 'Size': 'Small'}, {'Color': 'Yellow', 'Size': 'Medium'}, {'Color': 'Yellow', 'Size': 'Large'}] 
+22
source

You can get this result:

 x={'Color': ['Red', 'Yellow'], 'Size': ['Small', 'Medium', 'Large']} keys=x.keys() values=x.values() matrix=[] for i in range(len(keys)): cur_list=[] for j in range(len(values[i])): cur_list.append({keys[i]: values[i][j]}) matrix.append(cur_list) y=[] for i in matrix[0]: for j in matrix[1]: y.append(dict(i.items() + j.items())) print y 

result:

 [{'Color': 'Red', 'Size': 'Small'}, {'Color': 'Red', 'Size': 'Medium'}, {'Color': 'Red', 'Size': 'Large'}, {'Color': 'Yellow', 'Size': 'Small'}, {'Color': 'Yellow', 'Size': 'Medium'}, {'Color': 'Yellow', 'Size': 'Large'}] 
+1
source

All Articles