30

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'}
]
2
  • This would be a good question if you showed us what you've tried.
    – msvalkon
    Mar 4, 2013 at 21:54
  • 4
    I'd say this is a good question in any case because it's not easy to come up with the right concept here. Mar 4, 2013 at 22:00

2 Answers 2

49

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'}]
4
  • 2
    +1. Good to know that Python iterates over the dictionary items in the same, reproducible order, both for the zip() and the .values()! Mar 4, 2013 at 21:59
  • 3
    @TimPietzcker: yes, this property is documented and can be relied on. The order itself is arbitrary, but no compliant Python implementation can violate the guarantee that if you don't modify d, d.keys() (here d) and d.values() have to match.
    – DSM
    Mar 4, 2013 at 22:04
  • Thanks! This is perfect.
    – idnavid
    Jul 18, 2019 at 22:34
  • I think since python 3.7 the dict order is also not arbitrary anymore! See also here
    – Marti Nito
    Jun 7, 2021 at 16:09
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'}]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.