graham
graham

Reputation: 335

Looping through a dictionary using a generator in Python

I am trying to loop on a dictionary to find all the possible combinations, to be more specific, if I input {'a' : [1,2], 'b' : 3}, I want to get {'a' : 1, 'b' : 3} and {'a' : 2, 'b' : 3}.

I tried to write a generator that would work recursively :

def loop_dic(dic, head={}):

    if len(dic) == 0:
        yield head

    k = dic.keys()[0]
    vals = dic[k]
    dic.pop(k)
    if not hasattr(vals, '__iter__'):
        vals = [vals]

    for v in vals:
        _head = head.copy()
        _head.update({k:v})
        loop_dic(dic, _head)

but it doesn't work, as it gets a GeneratorExit: None at the first recursive call. How to do this?

Upvotes: 0

Views: 646

Answers (1)

zondo
zondo

Reputation: 20336

All you did is call loop_dic(); you didn't do anything with it. In Python 3, you can just do:

        yield from loop_dic(dic, _head)

In Python 2, you need a loop:

        for item in loop_dic(dic, _head):
            yield item

Upvotes: 2

Related Questions