Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all combinations of key/value pairs in Python dict

This may be a silly question, but given the following dict:

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

How would I achieve 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, irrespective of order.

like image 812
Andrew C Avatar asked Aug 10 '12 16:08

Andrew C


2 Answers

One solution is to use itertools.combinations():

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

Edit: Due to popular demand, here a Python 3.x version:

result_list = list(map(dict, itertools.combinations(
    combination_dict.items(), 2)))
like image 165
Jolly Jumper Avatar answered Nov 15 '22 21:11

Jolly Jumper


I prefer the solution by @JollyJumper for readability although this one performs 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
like image 24
jamylak Avatar answered Nov 15 '22 22:11

jamylak