I have two dictionaries, A
and B
. A
is a dictionary of dictionaries. The keys in the second level dictionaries match the keys in B
.
For example, A
could be:
A[key1][key_1] = 1
A[key1][key_2] = 4
A[key1][key_3] = 2
A[key2][key_2] = 5
A[key3][key_1] = 1
A[key3][key_3] = 2
and B
could be:
B[key_1] = 7
B[key_2] = 8
B[key_3] = 9
I've written a loop to multiply the values in each key of A
by B
for Akey in A.keys():
sum_Akey[Akey] = sum(map(lambda x: A[Akey][x]*B[x], B))
where sum_Akey
is a dictionary for storing the sums. It is keyed by the same values as the top level keys in A
.
For example: sum_Akey[key1] = 1*7 + 4*8 + 2*9 = 57
With a large enough A
and B
, this takes a really long time.
Out of curiosity, I removed the sum()
to see what would happen. Removing the sum()
makes it run much faster. I tried other approaches, e.g., making a list out of the map and then summing.
It appears that doing anything on the map object is the bottleneck.
Is there another, quicker way to get the sum of the values in the map
iterator?
Is there a faster way of getting the final sum?
NOTE: I found the Q&A just now. It answers one of my questions. python map, list(map), lambda and performance