Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Python Dictionary Permutations into List of Dictionaries

Given a dictionary that looks like this:

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

How can I create a list of dictionaries that combines the various values of the first dictionary's keys? What I want is:

[     {'Color': 'Red', 'Size': 'Small'},     {'Color': 'Red', 'Size': 'Medium'},     {'Color': 'Red', 'Size': 'Large'},     {'Color': 'Yellow', 'Size': 'Small'},     {'Color': 'Yellow', 'Size': 'Medium'},     {'Color': 'Yellow', 'Size': 'Large'} ] 
like image 843
user1272534 Avatar asked Mar 04 '13 21:03

user1272534


People also ask

Can you append dictionaries to lists?

Appending a dictionary to a list with the same key and different values. Using append() method. Using copy() method to list using append() method. Using deepcopy() method to list using append() method.

Can you merge dictionaries Python?

Python 3.9 has introduced the merge operator (|) in the dict class. Using the merge operator, we can combine dictionaries in a single line of code. We can also merge the dictionaries in-place by using the update operator (|=).

Can dictionary be convert to list in Python?

In Python, a dictionary provides method items() which returns an iterable sequence of all elements from the dictionary. The items() method basically converts a dictionary to a list along with that we can also use the list() function to get a list of tuples/pairs.


2 Answers

I think you want the 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'}] 
like image 133
DSM Avatar answered Oct 05 '22 22:10

DSM


You can obtain that result doing this:

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'}] 
like image 45
sissi_luaty Avatar answered Oct 05 '22 22:10

sissi_luaty