这可能是一个愚蠢的问题,但考虑到以下命令:
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/