Search code examples
listpython-3.xdictionarykey-value-storemultiplication

How to multiply the list values within a dictionary data type, while preserving the dictionary structure?


In the following dict (class, list):

defaultdict(<class 'list'>, {2480: ['0.25', '0.1', '0.083'], 2651: ['0.43', '0.11', '0.23']})
defaultdict(<class 'list'>, {2480: ['0.15', '0.15', '0.6'], 2651: ['0.26', '0.083', '0.23']})

I have tried:

for key, val in data.values():
    print(key, reduce(mul, (float(f) for f in val), 1))

This gives me error:

for key, val in data.values(): AttributeError: 'str' object has no attribute 'values

and also tried,

for k1 in data.items():
    print(k1)

This prints:

(2480, ['0.25', '0.1', '0.083']) (2651, ['0.43', '0.11', '0.23'])

but I am not able to multiply the float values with each other using reduce(mul() function.

I want to multiply the float values with each other but retain the class, list value preserved.

I want the output to be:

defaultdict(<class 'list'>, {2480: ['0.002075'], 2651: ['0.010879']})
defaultdict(<class 'list'>, {2480: ['0.0135'], 2651: ['0.0049634']})

but, the defaultdict(<class 'list' is kept here just to show the data structure.

Thanks,


Solution

  • You could first define a multiply function:

    >>> def multiply(*args):
    ...     res = args[0]
    ...     for arg in args[1:]:
    ...         res *= arg
    ...     return res
    

    If you only have two dicts:

    d1_product = {key: multiply(*map(float, values)) for key, values in d1.items()}
    d2_product = {key: multiply(*map(float, values)) for key, values in d2.items()}
    

    Although, if you have more than two dictionaries, you might want to try something like this (you'll have to modify it a bit to keep track of individual dicts, though... maybe try using enumerate, like so?

    res = {}
    for i, d in enumerate([d1, d2]):
        for key in d:
            values = map(float, d[key])
            product = multiply(*values)
            res[str(key) + str(i)] = product
    

    Which results in this:

    >>> res
    {'24801': 0.0135, '26511': 0.004963400000000001, '24800': 0.002075, '26510': 0.010879000000000002}