0

I am new to python. I'm extracting two rows from a csvfile.

Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, orange, carrot']

And the quantity list corresponds to each of the items in its sequence.

Quantity = ['1,2,1','2,5','1,2']

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.

I am trying to output:

{'Apple: totalquantity','Banana: totalquantity', 
 'Carrot: totalquantity','Chocolate: totalquantity',
 'orange: totalquantity', 'strawberry: totalquantity'}

Please help!

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

for cvs file is as follows:

row 1: apple, carrot, banana chocolate, apple strawberry, orange, carrot

row 2: 1,2,1 2,5 1,2

  • Does this answer your question? http://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe – Hannu Oct 13 '16 at 06:34
  • There are more foods listed in `Foodlist` than there are numbers in `Quantity`. Is this intended? Also, you should avoid naming things other than types with an uppercase identifier. – dkasak Oct 13 '16 at 06:52

2 Answers2

1

You can use Counter to aggregate the result:

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)

Output:

Counter({'apple': 6, 'chocolate': 2, 'carrot': 2, 'orange': 2, 'strawberry': 1, 'banana': 1})
niemmi
  • 17,113
  • 7
  • 35
  • 42
1

Use collections.default_dict to set up a dictionary to count your items in.

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]:
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73