2016-07-26 8 views
-1

私はカテゴリ別にグループ化されたすべての製品の平均価格を見つける必要があるCSVファイルを持っています。私はファイルからすべての行をリストに入れました。 は今、私はこれをしようとしている:ファイル内のキーの辞書にあるキーに値を追加する方法はありますか? Python

FILE_NAME = 'catalog_sample.csv' 
full_catalog = [] 

with open(FILE_NAME, encoding='utf-8') as file: 
    for line in file:    
     one_record = line.split(',') 
     full_catalog.append(one_record) 

category_dict = {} 
prices = [] 

for i in full_catalog: 
    if str(i[-2]) not in category_dict: 
     category_name = str(i[-2]) 
     category_dict[category_name] = float(i[-1]) 
    else: 
     prices.append(float(i[-1])) 

これまでのところ私は、キーとして、ファイルからすべてのカテゴリで辞書を取得していますが、その値は、ファイル内のキーの最初の発生から価格です。

'Men': 163.99 
'Women': 543.99 

私が(キーに値を追加する)期待していて、「他には」動作していないようです。助言がありますか?ありがとう!

+0

何か試しましたか? – Julien

+0

たくさんのものが、働いた人はいませんでした。私はそれらを共有しないことに決めました。 – skipper

+0

どのように要素をpython 'list'に追加しますか、それを知っていますか? – elelias

答えて

0

リストに追加して辞書に戻す代わりに、辞書を作成することをお勧めします。

category_dict = {} 
full_catalog = [] 

with open(FILE_NAME, encoding='utf-8') as file: 
    for line in file: 
     item = line.split(',') 
     # Unpack the last 2 items from list 
     category = item[-2].strip() 
     price = float(item[-1]) 

     # Try get the list of prices for the category 
     # If there is no key matching category in dict 
     # Then return an empty list 
     prices = category_dict.get(category, []) 
     # Append the price to the list 
     prices.append(price) 

     # Set the list as the value for the category 
     # If there was no key then a key is created 
     # The value is the list with the new price 
     category_dict[category] = prices 
     full_catalog.append(item) 

編集:提供された行形式に一致するように修正されました。 full_catalogはまだリスト全体が必要な場合に含まれています

+0

ありがとうございます! – skipper

関連する問題