You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何从动态长度字典生成所有键值组合的拼接字符串列表

实现方案

核心思路是调用Python标准库itertools的product方法生成所有值列表的笛卡尔积,再按要求拼接字符串,不需要提前知道字典的键数量和每个值列表的长度。

完整代码示例

import itertools

def generate_target_list(input_dict):
    # 提取键列表,Python3.7+默认保留字典插入顺序,低版本可替换为 sorted(input_dict.keys()) 固定排序
    keys = list(input_dict.keys())
    # 生成所有值列表的笛卡尔积
    all_combinations = itertools.product(*input_dict.values())
    # 按格式拼接字符串
    return [
        ' '.join(f"{key} {val}" for key, val in zip(keys, combo))
        for combo in all_combinations
    ]

# 测试用例
a = {'test1': ['1','2','3'], 'test2': ['11', '22'], 'test3': ['33']}
print(generate_target_list(a))

输出结果

运行上述代码得到的输出和需求完全一致:

['test1 1 test2 11 test3 33', 'test1 1 test2 22 test3 33', 'test1 2 test2 11 test3 33', 'test1 2 test2 22 test3 33', 'test1 3 test2 11 test3 33', 'test1 3 test2 22 test3 33']

说明

  • itertools.product接收任意数量的可迭代对象作为参数,自动生成所有元素的组合,适配任意数量的键、任意长度的值列表场景
  • 如果需要保证键的排序稳定,把keys = list(input_dict.keys())替换为keys = sorted(input_dict.keys()),同时把笛卡尔积生成部分改为itertools.product(*[input_dict[k] for k in keys])即可。

内容的提问来源于stack exchange,提问作者Mark Frayhard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:45:05