将Python字典排列组合到词典列表中 [英] Combine Python Dictionary Permutations into List of Dictionaries
本文介绍了将Python字典排列组合到词典列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
{
'颜色':['红','黄色']
'Size':['Small','Medium','Large']
}
如何创建一个组合第一个字典键的各种值的字典列表?我想要的是:
[
{'Color':'Red','Size' },
{'Color':'Red','Size':'Medium'},
{'Color':'Red','Size':'Large'},
{'Color':'Yellow','Size':'Small'},
{'Color':'Yellow','Size':'Medium'},
{'Color'黄色','大小':'大'}
]
解决方案
我想你想要笛卡尔乘积,而不是排列,在这种情况下, itertools.product
可以帮助:
>>>来自itertools import product
>>>> d = {'Color':['Red','Yellow'],'Size':['Small','Medium','Large']}
>>>对于v in product(* d.values())中的[dict(zip(d,v))]
[{'Color':'Red','Size':'Small'},{'Color' :'''''''''''''''''''''''''''''''''' {'Color':'Yellow','Size':'Medium'},{'Color':'Yellow','Size':'Large'}]
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'}
]
解决方案
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'}]
这篇关于将Python字典排列组合到词典列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文