[Python] Python - cartesian product for BOTH keys and values of a dictionary? [MWE provided]

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    I need to get the Cartesian product of a dictionary {str: Fraction} with itself, but currently need to "loop" through the dict twice, once for the keys and once for the values.

    The difference is that a tuple output works well for the keys, but for the values I actually need the regular math product.

    How can I do better? Keen to stick to the standard library if possible.

    import itertools as it
    import math as mt
    from fractions import Fraction as fr

    dl = {
    'P1': fr(7, 120), 'P2': fr(20, 120), 'P3': fr(6, 120),
    'P4': fr(10, 120), 'P6': fr(7, 120), 'P6': fr(18, 120),
    'P7': fr(16, 120), 'P8': fr(19, 120), 'P9': fr(17, 120)
    }
    rp = 2
    iter_args = list(it.product(dl, repeat = rp))
    iter_vals = list(map(mt.prod, it.product(dl.values(), repeat = rp)))

    # Desired output
    print({iter_keys: iter_vals for i in range(len(iter_vals))})


    Thank you!

    Continue reading...

Compartilhe esta Página