Combine Python Dictionary Permutations into List of Dictionaries

后端 未结 2 631
误落风尘
误落风尘 2020-12-01 09:06

Given a dictionary that looks like this:

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

How can

相关标签:
2条回答
  • 2020-12-01 10:02

    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 讨论(0)
  • 2020-12-01 10:06

    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'}]
    
    0 讨论(0)
提交回复
热议问题