2016-10-13 17 views
0

私はPythonの初心者です。私はcsvfileから2つの行を抽出しています。Python辞書に共通のキーを持つ2つのリストを追加する

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

そして、数量リストは、その順序で各項目に対応する。

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

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

「フードリスト'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]: 
関連する問題