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>Use collections.default_dict to set up a dictionary to count your items in.</p>

<pre><code>In [1]: from collections import defaultdict

In [2]: items = defaultdict(int)

In [3]: Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, or
   ...: ange, carrot']

In [4]: Quantity = ['1,2,1','2,5','1,2']

In [5]: for which, counts in zip(Foodlist, Quantity):
   ...:     foods = [w.strip() for w in which.split(',')]  # Split the foods and remove trailing spaces
   ...:     nums = [int(c) for c in counts.split(',')]  # Split the counts are convert to ints
   ...:     for f, n in zip(foods, nums):
   ...:         items[f] += n
   ...:

In [6]: items
Out[6]:
defaultdict(int,
            {'apple': 6,
             'banana': 1,
             'carrot': 2,
             'chocolate': 2,
             'orange': 2,
             'strawberry': 1})

In [7]:
</code></pre>

python list csv dictionary key