Search code examples
pythonpython-3.xdictionarylist-comprehensiondict-comprehension

Multiply key of the same dict


I'm using python 3.5, I need to multiply this dict and this should output the result of multiplication of each key of dict.

{0: [0.0008726003490401396, 0.004363001745200698, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0017452006980802793, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396], 1: [0.007853403141361256, 0.008726003490401396, 0.0008726003490401396], 2: [0.004363001745200698, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396, 0.007853403141361256, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.002617801047120419, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.002617801047120419, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.002617801047120419, 0.0034904013961605585, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.002617801047120419, 0.0008726003490401396, 0.0034904013961605585, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396]}

This is my try but does not work:

lista = {k: [v*v for v in v] for k, v in lista.items()}

the output i would is for example:

{0: [0.068726003490401396], 1: [0.077853403141361256, 2: [0.098363001745200698]}

Solution

  • Using dictionary comprehension and functools.reduce + operator.mul:

    >>> from functools import mul
    >>> mul(3, 4)  # == 3 * 4
    12
    
    >>> from functools import reduce
    >>> reduce(mul, [3, 4, 2])  # == (3 * 4) * 2
    24
    

    >>> from functools import reduce
    >>> from operator import mul
    >>>
    >>> lista = {
    ...     0: [0.0008726003490401396, 0.004363001745200698],
    ...     1: [0.007853403141361256, 0.008726003490401396, 0.0008726003490401396],
    ...     2: [0.004363001745200698, 0.0008726003490401396, 0.0008726003490401396],
    ... }
    >>>
    >>> {key: reduce(mul, value) for key, value in lista.items()}
    {0: 3.8071568457248673e-06, 1: 5.979827506374137e-08, 2: 3.322126392430076e-09}
    >>> {key: [reduce(mul, value)] for key, value in lista.items()}
    {0: [3.8071568457248673e-06], 1: [5.979827506374137e-08], 2: [3.322126392430076e-09]}