Python Adding 2 list with common keys to dictionary
<p>I am new to python. I'm extracting two rows from a csvfile.</p>

<pre><code>Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']
</code></pre>

<p>And the quantity list corresponds to each of the items in its sequence.</p>

<pre><code>Quantity = ['1,2,1','2,5','1,2']
</code></pre>

<p>How can i merge the two list with common keys into a dictionary? I tried splitting and joining but the quantity gets overwritten due to the common keys. </p>

<p>I am trying to output: </p>

<pre><code>{'Apple: totalquantity','Banana: totalquantity', 
 'Carrot: totalquantity','Chocolate: totalquantity',
 'orange: totalquantity', 'strawberry: totalquantity'}
</code></pre>

<p>Please help! </p>

<p>Will there be anyway where i can extract the csvfile row for the food items and assign its values in a dictionary? </p>

<p>for cvs file is as follows:</p>

<p>row 1:
apple, carrot, banana 
chocolate, apple
strawberry, orange, carrot</p>

<p>row 2: 
1,2,1
2,5
1,2</p>

<p>You can use <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> to aggregate the result:</p>

<pre><code>from collections import Counter

Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']
Quantity = ['1,2,1','2,5','1,2']
res = Counter()

for f_list, q_list in zip(Foodlist, Quantity):
    for f, q in zip(f_list.split(', '), q_list.split(',')):
        res[f] += int(q)

print(res)
</code></pre>

<p>Output:</p>

<pre><code>Counter({'apple': 6, 'chocolate': 2, 'carrot': 2, 'orange': 2, 'strawberry': 1, 'banana': 1})
</code></pre>

python list csv dictionary key