2012-08-10 71 views
4

这可能是一个愚蠢的问题,但考虑到以下字典:获取键/值对的所有组合在Python字典

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

在其他单词,我想要一个字典中的两个键/值对的所有组合,无需替换,无论顺序如何。

+6

为什么没有' “两个”'/' “三”'在'result_list'? – 2012-08-10 16:20:11

+1

谢谢指出! – 2012-08-10 16:42:16

回答

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))) 
+0

+1。除非有特别的理由否则,我倾向于在python 2和3之间使代码更加便携。我会使用'dict.items()'_unless_存在内存问题。 – 2012-08-10 16:28:04

+0

@JoelCornett如果你正在考虑3.x,那么你还必须将'map'对象转换为'list',所以最好留下这个备注 – jamylak 2012-08-10 16:29:17

+4

@JoelCornett:是的,没关系。我猜如果我使用'items()'而不是'iteritems()',有人会评论说这会浪费内存。 (老实说,如果字典很大,需要指向所有键和值的指针副本是一个问题,那么您肯定不想创建使用O(n2)额外空间的两个项目的所有组合。) – 2012-08-10 16:32:25

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 
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]}] 
相关问题