python - 在 Python 字典中获取键/值对的所有组合

标签 python list dictionary combinations

这可能是一个愚蠢的问题,但考虑到以下命令:

combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}

我将如何实现这个列表:

result_list = [{"one": [1, 2, 3], "two": [2, 3, 4]}, {"one": [1, 2, 3], "three": [3, 4, 5]}, {"two": [2, 3, 4], "three": [3, 4, 5]}]

换句话说,我希望字典中两个键/值对的所有组合都无需替换,无论顺序如何。

最佳答案

一种解决方案是使用 itertools.combinations():

result_list = map(dict, itertools.combinations(
    combination_dict.iteritems(), 2))

编辑:由于popular demand ,这里是 Python 3.x 版本:

result_list = list(map(dict, itertools.combinations(
    combination_dict.items(), 2)))

关于python - 在 Python 字典中获取键/值对的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11905573/

相关文章:

python - 无法在 OpenCV python 中打开视频文件

python - 将 bash/shell 行转换为 python 2.6

python - sphinx 警告 : autosummary: stub file not found for the methods of the class. 检查您的 autosummary_generate 设置

python - 如何根据字典键定义变量名?

python - Pandas 数据框的几个字典列表

python - 在保留字典的同时将字典值转换为集合

python - 满足这个标准的语言?

python - 如何使用Python中的列表理解从一个元素中获取多个元素?

python - 从键列表中获取字典中的所有值,其中相同的键多次出现

python - 从列表中删除整个列表