Home > OS >  Iterating over combinations of integer values from a dict
Iterating over combinations of integer values from a dict

Time:09-29

I have a dict I'm trying to loop through which stores integer values:

myDict = {"a":1,"b":2,"c":3}

And I'm trying to loop through every combination of these integers from 1 to their value. For example:

{"a":1,"b":1,"c":1}
{"a":1,"b":1,"c":2}
{"a":1,"b":1,"c":3}
{"a":1,"b":2,"c":1}
{"a":1,"b":2,"c":2}
And so on...

Ending at their max values at the start while going through all the combinations.

Is there an elegant way to this that applies to any size dictionary? :

myDict = {"a":1,"b":2,"c":3,"d":5}

I'm currently doing this with nested if statements that edit a clone dictionary, so any solution setting dict values would work :) :

copyDict["c"] = 2

CodePudding user response:

Yes, this will do it, for any size input (that fits in memory, of course):

import itertools

myDict = {"a":1,"b":2,"c":3,"d":5}
keys = list(myDict.keys())
ranges = tuple(range(1,k 1) for k in myDict.values())

outs = [dict(zip(keys,s)) for s in itertools.product(*ranges)]
print(outs)

You can actually replace *ranges with the *(range(1,k 1) for k in myDict.values()) and reduce it by one line, but it's not easier to read.

CodePudding user response:

Another way with itertools.product:

>>> [dict(zip(myDict.keys(), p)) for p in itertools.product(myDict.values(), repeat=len(myDict))]
[{'a': 1, 'b': 1, 'c': 1},
 {'a': 1, 'b': 1, 'c': 2},
 {'a': 1, 'b': 1, 'c': 3},
 {'a': 1, 'b': 2, 'c': 1},
 {'a': 1, 'b': 2, 'c': 2},
 {'a': 1, 'b': 2, 'c': 3},
 {'a': 1, 'b': 3, 'c': 1},
 {'a': 1, 'b': 3, 'c': 2},
 {'a': 1, 'b': 3, 'c': 3},
 {'a': 2, 'b': 1, 'c': 1},
 {'a': 2, 'b': 1, 'c': 2},
 {'a': 2, 'b': 1, 'c': 3},
 {'a': 2, 'b': 2, 'c': 1},
 {'a': 2, 'b': 2, 'c': 2},
 {'a': 2, 'b': 2, 'c': 3},
 {'a': 2, 'b': 3, 'c': 1},
 {'a': 2, 'b': 3, 'c': 2},
 {'a': 2, 'b': 3, 'c': 3},
 {'a': 3, 'b': 1, 'c': 1},
 {'a': 3, 'b': 1, 'c': 2},
 {'a': 3, 'b': 1, 'c': 3},
 {'a': 3, 'b': 2, 'c': 1},
 {'a': 3, 'b': 2, 'c': 2},
 {'a': 3, 'b': 2, 'c': 3},
 {'a': 3, 'b': 3, 'c': 1},
 {'a': 3, 'b': 3, 'c': 2},
 {'a': 3, 'b': 3, 'c': 3}]
  • Related