Andrew C
Andrew C

Reputation: 699

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.

Upvotes: 9

Views: 17684

Answers (4)

Jolly Jumper
Jolly Jumper

Reputation: 776

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

Upvotes: 21

jamylak
jamylak

Reputation: 133544

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

Upvotes: 1

angs
angs

Reputation: 439

I believe this would get you what you need.

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

I found this tutorial to be very helpful:

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

Upvotes: -2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

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

Upvotes: 0

Related Questions