2016-10-13 55 views
0

我是python的新手。我從csvfile中提取兩行。Python將常用鍵添加到列表中的2個列表

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

並且數量列表對應於其序列中的每個項目。

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

如何將兩個列表與常用鍵合併到字典中?我嘗試了拆分和加入,但由於常用密鑰而導致數量被覆蓋。

我試圖輸出:

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

請幫幫忙!

無論如何,我可以提取csvfile行的食品項目,並在字典中指定其值?

爲CVS文件如下:

行1: 蘋果,胡蘿蔔,蕉 巧克力,蘋果 草莓,橘子,胡蘿蔔

行2: 1,2,1 2, 5 1,2

+0

這是否回答你的問題? http://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe – Hannu

+0

有更多的食物列入'Foodlist ''Quantity'中有數字。這是打算?另外,你應該避免命名具有大寫標識符的類型以外的東西。 – dkasak

回答

1

您可以使用Counter彙總結果:

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) 

輸出:

Counter({'apple': 6, 'chocolate': 2, 'carrot': 2, 'orange': 2, 'strawberry': 1, 'banana': 1}) 
1

使用collections.default_dict建立一個字典中算你的項目

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]: