'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'}
]
Solution 1:[1]
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'}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sissi_luaty |
