将 Python 字典排列组合成字典列表 [英] Combine Python Dictionary Permutations into List of Dictionaries

查看:29
本文介绍了将 Python 字典排列组合成字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个看起来像这样的字典:

<代码>{'颜色':['红色','黄色'],'尺寸':['小'、'中'、'大']}

如何创建一个字典列表来组合第一个字典键的各种值?我想要的是:

<预><代码>[{'颜色':'红色','尺寸':'小'},{'颜色':'红色','尺寸':'中'},{'颜色':'红色','尺寸':'大'},{'颜色':'黄色','尺寸':'小'},{'颜色':'黄色','尺寸':'中'},{'颜色':'黄色','尺寸':'大'}]

解决方案

我认为你想要笛卡尔积,而不是排列,在这种情况下 itertools.product 可以提供帮助:

<预><代码>>>>从 itertools 导入产品>>>d = {'颜色':['红色','黄色'],'尺寸':['小','中','大']}>>>[dict(zip(d, v)) for v in product(*d.values())][{'颜色':'红色','大小':'小'},{'颜色':'红色','大小':'中'},{'颜色':'红色','大小':'大'},{'颜色':'黄色','尺寸':'小'},{'颜色':'黄色','尺寸':'中'},{'颜色':'黄色','尺寸':'大'}]

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆