-1

My goal is to build all possible combinations between the keys in a dictionary (plus a few other rules that don't really matter), so I wrote the recursive function bellow.

dict = {3: 54, 37: 100, 56: 33}

def dosomething(dict, indent, stop, position):
    if dict == {} or stop <0:
        return

    keys = dict.keys()
    for k in keys:
        if k > position:
            print indent, k
            dosomething(dict, indent + "    ", stop -1, k)

indent = " "
dosomething(dict, indent, 4, 0)

Printing the result show the values I want:

 56
 3
     56
     37
         56
 37
     56

but now I'd like to have them in a list of lists where the elements would be:

[56]
[3,56]
[3,37,56]
[37,56]

Would anyone be able to help me with that?

Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117
Diego
  • 34,802
  • 21
  • 91
  • 134

1 Answers1

3

The following will generate a list of all possible combinations of keys

import itertools

dict = {3: 54, 37: 100, 56: 33}

combos = []

for i in range(len(dict.keys())):

    combos.extend([sorted(l) for l in itertools.combinations(dict.keys(), i+1)])

print combos

Will return:

[[56], [3], [37], [56, 3], [56, 37], [3, 37], [56, 3, 37]]
Constantino
  • 2,243
  • 2
  • 24
  • 41