Search code examples
pythonpermutation

Passing dictionary permutations to a function as inputs


I have a function like the following:

def function_name(a, b, c):
    # Do some stuff with a, b, and c
    print(result)

I've generated several dictionaries like these:

dict1 = {25: 1015, 36: 1089, 41: 1138}
dict2 = {12: 2031, 25: 2403, 31: 2802}
dict3 = {12: 3492, 28: 3902, 40: 7843}

I can generate all possible permutations with a range of 3 for these dictionaries, but I can't seem to feed them into my function as inputs. I can print the combinations like this:

print([x for x in itertools.permutations(['dict1', 'dict2', 'dict3'], 3)])

which correctly generates:

[('dict1', 'dict2', 'dict3'), ('dict1', 'dict3', 'dict2'), ('dict2', 'dict1', 'dict3'), ('dict2', 'dict3', 'dict1'), ('dict3', 'dict1', 'dict2'), ('dict3', 'dict2', 'dict1')]

But when I try to feed each group from the permutation result as a, b, and c in my function by using:

data = [x for x in itertools.permutations([dict1, dict2, dict3], 3)]
function_name(data)

I get this:

TypeError: function_name() missing 2 required positional arguments: 'b', and 'c'

I also tried to define the function to accept **data as an input, but that results in this:

function_name(**data)
TypeError: __main__.function_name() argument after ** must be a mapping, not list

How can I pass the permutations of my dictionary to my function as inputs?


Solution

  • Your data is a list of the dicts permutations (6 elements, each being a tuple of the three dicts). If you mean to feed each permutation (not all of them all at once) to your function, you need a loop for that:

    Either:

    data = [x for x in itertools.permutations([dict1, dict2, dict3], 3)]
    results = [function_name(a, b, c) for a, b, c in data]
    

    Or directly, so you don't have to store the permutations themselves:

    results = [
        function_name(a, b, c)
        for a, b, c in itertools.permutations([dict1, dict2, dict3], 3)
    ]