Mark K
Mark K

Reputation: 9348

Python, print out keys of element sums of each possible combinations in a dictionary

Below lines are created to iterate and sum each possible element combinations in a dictionary. For example, if the length of dictionary is 5, I want the sum of any 2 elements, any 3 elements, any 4 elements.

import itertools

di = {'a': 1, 'b': 2, 'c': 34, 'd': 24}

dict_len = range(len(di)-2, len(di))

for l in dict_len:
    d_values = list(itertools.combinations(di.values(), l))
    for d in d_values:
        print d

Output:

35
3
25
36
58
26
37
59
27
60

How can I have the keys of the values print out as well? like:

a + c = 35
a + b = 3
a + d = 25
b + c = 36
c + d = 58
b + d = 26
a + b + c =37
a + c + d =59
a + b + d =27
c + b + d =60

Thank you.

Upvotes: 2

Views: 71

Answers (3)

Ma0
Ma0

Reputation: 15204

Interesting problem. You can do it like this:

import itertools

di = {'a': 1, 'b': 2, 'c': 34, 'd': 24}

for n in range(2, len(di)):
  for pairs in itertools.combinations(di.items(), n):
      keys, values = zip(*pairs)  # Note 1
      print("{} = {}".format(' + '.join(keys), sum(values)))

which results in

a + b = 3
a + c = 35
a + d = 25
b + c = 36
b + d = 26
c + d = 58
a + b + c = 37
a + b + d = 27
a + c + d = 59
b + c + d = 60

Notes:

  1. Notice the zip(*iterable) construction which changes the grouping order. For instance it takes you from [('foo', 1), ('bar', 2)] to [('foo', 'bar'), (1, 2)] thus effectively grouping the keys and values together.

Upvotes: 1

lyxal
lyxal

Reputation: 1118

To get your desired output (as specified in the question):

import itertools

di = {'a': 1, 'b': 2, 'c': 34, 'd': 24}

dict_len = range(len(di)-2, len(di))

for l in dict_len:
    d_values = list(itertools.combinations(di.values(), l))
    d_keys = list(itertools.combinations(di.keys(), l))
    for i in range(len(d_values)):
        print " + ".join(d_keys[i]), "=", sum(d_values[i])

Output:

a + c = 35
a + b = 3
a + d = 25
c + b = 36
c + d = 58
b + d = 26
a + c + b = 37
a + c + d = 59
a + b + d = 27
c + b + d = 60

Upvotes: 1

Shintlor
Shintlor

Reputation: 812

You could something like this:

di = {'a': 1, 'b': 2, 'c': 34, 'd': 24}

dict_len = range(len(di)-2, len(di))

for l in dict_len:
    d_values = list(itertools.combinations(di.values(), l))
    d_keys =  list(itertools.combinations(di.keys(), l))
    for d,k in zip(d_values,d_keys):
        print(k,sum(d))

Which generates the output:

('a', 'b') 3
('a', 'c') 35
('a', 'd') 25
('b', 'c') 36
('b', 'd') 26
('c', 'd') 58
('a', 'b', 'c') 37
('a', 'b', 'd') 27
('a', 'c', 'd') 59
('b', 'c', 'd') 60

Upvotes: 1

Related Questions