获取键/值对的所有组合在Python字典(Getting all combinations of k

2019-06-26 22:54发布

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

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]}]

换句话说,我想在一个字典两个关键/值对的所有组合,无需更换,不论顺序。

Answer 1:

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

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

编辑 :由于大众需求 ,这里一个Python 3.x版:

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


Answer 2:

我通过@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


Answer 3:

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]}]


Answer 4:

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

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/



文章来源: Getting all combinations of key/value pairs in Python dict