- 3 months ago 20
Python Question

Summing over an array and then multiply by a dictionary

Fruits = ['apple', 'orange', 'banana', 'kiwi']

A = [4, 3, 10, 8]

B = {'apple': {'Bill': 4, 'Jan': 3, 'Frank': 5},
'orange': {'Bill': 0, 'Jan': 1, 'Frank': 5},
'banana': {'Bill': 8, 'Jan': 6, 'Frank': 2},
'kiwi': {'Bill': 4, 'Jan': 2, 'Frank': 7}}

I am trying to sum over all the fruits of A and multiply that by B. I am having trouble doing this A is an array of just numbers and B is a dictionary. This is where I am getting confused. I am a new Python user. The numbers in A are in the same position relative to Fruits (the first number in A is the number of apples). Would this involve using sum(A)?

Sorry folks for the lack of details. Here is some clarity. I have fruits and I have numbers of fruits that each person has based on the type. I am wanting to sum all of the values of each fruit type in B such that I get:

apple = 12
orange = 6
banana = 16
kiwi = 13

Now, I want to multiple these numbers, by A, but keeping in mind that the first number in A, is apple, then orange, and so on to get a new array:

Solution = [48,18,160,104] #solution order is apple, orange, banana, kiwi


Assuming that you want to multply the sum of the fruits for each person (in B) by the cost in A, you can do the following list comprehension:

>>> [cost * sum(B[fruit].values()) for cost, fruit in zip(A, Fruits)]
[48, 18, 160, 104]