-1

I have a dictionary, which at the moment has 2 keys, but could have more (Each key will always have a single list with the amount of values they are).

I need to do the following operation:

If in the first key I have 2 values in my list, and in the second key I have a value in my list, then I am looking to multiply those values, example:

dict_v = {1: ['12X58', '14X53'], 2: ['10X60']}

total = 2 * 1 = 2

If I had a 3 key dictionary:

dict_v = {1: ['12X58', '14X53'], 2: ['10X60'], 3: ['8X58', '8X67', '10X49', '10X54']}

total = 2 * 1 * 4 = 8

I would greatly appreciate the help provided, kind regards.

5 Answers 5

3

You can do the following:

import math 

dict_v = {1: ['12X58', '14X53'], 2: ['10X60'], 3: ['8X58', '8X67', '10X49', '10X54']}

print(math.prod([len(v) for v in dict_v.values()]))
1
  • Thanks, i tried with numpy bookstore, you gave me a great idea, best regards.
    – DaniV
    Jun 22, 2020 at 12:52
1

Use the reduce function to calculate the multiplication of the len of the dictionary values.

dict_v = {1: ['12X58', '14X53'], 2: ['10X60'], 3: ['8X58', '8X67', '10X49', '10X54']}
total = reduce(lambda x,y: x*y, map(len, dict_v.values()))
1

You can use functools.reduce to multiply the lengths of all the list values (obtained by mapping len to each value):

from functools import reduce

dict_v = {1: ['12X58', '14X53'], 2: ['10X60']}

print(reduce(lambda c, v: c * v, map(len, dict_v.values())))

dict_v = {1: ['12X58', '14X53'], 2: ['10X60'], 3: ['8X58', '8X67', '10X49', '10X54']}

print(reduce(lambda c, v: c * v, map(len, dict_v.values())))

Output

2
8
1

This one may not be so Pythonic but it illustrates the steps well

# Set the initial value of your variable to 1 (as you will do multiplication with it)
total = 1

# With the following line you will create a list of all the values in your dictionary (each value is a list)
# Then multiply the current value of your "total" variable with the LENGTH of each list

for value in dict_v.values():
    total *= len(value)

print(total)
1

Without map(),the faster way could be:

from functools import reduce

dict_v = {1: ['12X58', '14X53'], 2: ['10X60']}
print(reduce(lambda x, y: len(x) * len(y), dict_v.values()))

map will cost extra overhead.


By Test(timeit.timeit:number = 100):

# print(reduce(lambda x, y: len(x) * len(y), dict_v.values()))
4.309999999996261e-05

# print(reduce(lambda c, v: c * v, map(len, dict_v.values())))
5.319999999997549e-05

Not sure math.prod.I couldn't run it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.