Getting all key / value pair combinations in Python dict

This might be a dumb question, but given the following dict:

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

How do I reach this list:

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

In other words, I want all combinations of two key / value pairs in a dict without replacement, regardless of order.

+4
source share
4 answers

One solution is to use itertools.combinations() :

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

Edit : due to popular demand , here is the Python version 3.x:

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

I prefer @JollyJumper's solution for readability, although this is faster

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

Timings:

 >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 
+1
source
 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 

output:

 [{'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]}] 
0
source

I believe that this will bring you what you need.

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

I found this tutorial very useful:

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

-2
source

All Articles