在Python中获取键/值对的所有组合

时间:2012-08-10 16:17:59

标签: 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]}]

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

4 个答案:

答案 0 :(得分:14)

一种解决方案是使用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)))

答案 1 :(得分:1)

我更喜欢@JollyJumper的解决方案,虽然这个解决方案性能更快

>>> from itertools import combinations
>>> d = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}
>>> [{j: d[j] for j in i} for i in combinations(d, 2)]
[{'three': [3, 4, 5], 'two': [2, 3, 4]}, {'three': [3, 4, 5], 'one': [1, 2, 3]}, {'two': [2, 3, 4], 'one': [1, 2, 3]}]

时序:

>python -m timeit -s "d = {'three': [3, 4, 5], 'two': [2, 3, 4], 'one': [1, 2, 3]}; from itertools import combinations" "map(dict, combinations(d.iteritems(), 2))"
100000 loops, best of 3: 3.27 usec per loop

>python -m timeit -s "d = {'three': [3, 4, 5], 'two': [2, 3, 4], 'one': [1, 2, 3]}; from itertools import combinations" "[{j: d[j] for j in i} for i in combinations(d, 2)]"
1000000 loops, best of 3: 1.92 usec per loop

答案 2 :(得分:0)

from itertools import combinations
combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}
lis=[]
for i in range(1,len(combination_dict)):
    for x in combinations(combination_dict,i):
        dic={z:combination_dict[z] for z in x}
        lis.append(dic)
print lis            

<强>输出:

[{'three': [3, 4, 5]}, {'two': [2, 3, 4]}, {'one': [1, 2, 3]}, {'three': [3, 4, 5], 'two': [2, 3, 4]}, {'three': [3, 4, 5], 'one': [1, 2, 3]}, {'two': [2, 3, 4], 'one': [1, 2, 3]}]

答案 3 :(得分:-2)

我相信这会得到你所需要的。

result list = [{combination_dict['one','two'],combination_dict['one','three']}]

我发现本教程非常有用:

http://bdhacker.wordpress.com/2010/02/27/python-tutorial-dictionaries-key-value-pair-maps-basics/